当前位置:   article > 正文

KeyStorte存储Rsa非对称加密秘钥_java keystore存储rsa密钥

java keystore存储rsa密钥

一、 RSA:非对称加密是一种加密方式,加密和解密使用不同的密钥。发送方使用公钥进行加密,接收方使用私钥进行解密。因为公钥可以公开,所以只有私钥知道的加密信息能够被解密,这种方式的优点是安全性高,缺点是相对于对称加密而言,加密速度较慢。

        

        Keystore:在Java中,keystore是用于存储密钥、证书和信任项的安全存储库。它通常用于管理SSL证书、数字证书和私钥,以便在加密通信、数字签名和认证等安全领域使用。

具体来说,keystore可以用于以下几个方面:

  1. 存储SSL证书和私钥,用于安全通信。在使用HTTPS协议进行加密通信时,服务器和客户端都需要从keystore中加载SSL证书和私钥。
  2. 存储数字证书,用于数字签名和认证。数字证书可以用于验证通信双方的身份,防止中间人攻击。
  3. 存储信任项,用于信任其他实体的证书。在建立SSL连接时,客户端需要信任服务器的证书,服务器需要信任客户端的证书,这些信任项可以从keystore中加载。

二、实际应用


KeyStore是一个存储库,可用于存储一系列密钥(Secret Key)、密钥对(Key Pair)或证书(Certificate)

密钥:只有一个钥,一般是对称加密时使用。
密钥对:包含公钥(Public Key)和私钥(Private Key),一般是非对称加密时使

KeyStore可以设置密码。
密钥、密钥对、证书在KeyStore统称为Key(又称"条目"),每一个Key通过alias(别名)区分。Key也可以设置密码。
KeyStore可以理解为一种规范,常见的 JKS(Java Key Store)只是KeyStore的一种实现类型,其他的还有PKCS12、JCEKS等。
JKS 可以存储密钥对和证书,但不能用于存储密钥。
PKCS12、JCEKS 都可以存储密钥对、证书、密钥。

命令方式生成Keystore:

  1. #命令方法生成keystore JDK bin cmd
  2. .\keytool.exe -genkeypair
  3.   -alias dataKeystore  //定义的别名,不可重复
  4.   -keypass password123!@#  //设置密钥对的密码,这个密码用于保护私钥
  5.   -keyalg RSA  //指定生成的密钥对算法为RSA
  6.   -keysize 2048  //指定RSA密钥的大小为2048位
  7.   -validity 9999  //指定密钥的有效期 天
  8.   -keystore D:\dataKeystore\dataKeystore.keystore  //指定密钥库的路径和文件名
  9.   -storepass admin-test  //密钥库的密码,用于保护密钥库中的密钥对
  10. #创建keystore
  11. .\keytool.exe -genkeypair -alias dataKeystor -keypass password123!@# -keyalg RSA -keysize 2048 -validity 9999 -keystore D:\keystore\dataKeystor.keystore -storepass admin-test
  12. #查看密匙库
  13.  .\keytool.exe -list -rfc -keystore D:\keystore\dataKeystore.keystore -storepass admin-test


代码方式创建keystore:

  1. private static final int keysize = 2048;
  2. private static final String commonName = "www.baidi.com";
  3. private static final String organizationalUnit = "baidu";
  4. private static final String organization = "baidu";
  5. private static final String city = "hebei";
  6. private static final String state = "baoding";
  7. private static final String country = "CN";
  8. private static final long validity = 3650; //十年
  9. private static final String alias = "test";
  10. private static final char[] keyPassword = "1231312".toCharArray();
  11. private static final char[] storePassword = "1231231".toCharArray();
  12. private static final String path = CreateKeystore.class.getClassLoader().getResource(".").getPath();
  13. public static void main(String[] args) {
  14. createKeystore();
  15. }
  16. public static void createKeystore(){
  17. //获取文件地址
  18. try {
  19. KeyStore ks = KeyStore.getInstance("JKS");
  20. ks.load(null, null);
  21. CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
  22. X500Name x500Name = new X500Name(commonName, organizationalUnit, organization, city, state, country);
  23. keypair.generate(keysize);
  24. PrivateKey privateKey = keypair.getPrivateKey();
  25. X509Certificate[] chain = new X509Certificate[1];
  26. chain[0] = keypair.getSelfCertificate(x500Name, new Date(), (long)validity*24*60*60);
  27. FileOutputStream fos = new FileOutputStream(path+"OEM_Keystore.keystore");
  28. ks.setKeyEntry(alias, privateKey, keyPassword, chain);
  29. ks.store(fos, storePassword);
  30. fos.close();
  31. System.out.println("create Success");
  32. } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException |
  33. NoSuchProviderException | InvalidKeyException | SignatureException e ) {
  34. e.printStackTrace();
  35. }
  36. }

 java使用Keystore: 注意 导出公钥一般格式为:public_key.pem 私钥为(一般不可导出,仅为导出时示范):private_key.pem ,PEM(Privacy-Enhanced Mail)文件是一种常用的证书格式,通常用于存储加密证书、私钥和其他相关证书。PEM文件使用Base64编码表示,并包含"-----BEGIN CERTIFICATE-----"和"-----END CERTIFICATE-----"之间的文本块

  1. package com.gdc.encryption.util;
  2. /**
  3. * 公私钥获取,加解密工具类
  4. * @owner jiangliu
  5. * @Date: 2024/4/17 10:32
  6. */
  7. import org.apache.tomcat.util.codec.binary.Base64;
  8. import org.springframework.boot.autoconfigure.web.ServerProperties;
  9. import org.springframework.core.io.ClassPathResource;
  10. import sun.misc.BASE64Decoder;
  11. import sun.misc.BASE64Encoder;
  12. import javax.crypto.Cipher;
  13. import java.io.*;
  14. import java.net.URL;
  15. import java.nio.charset.StandardCharsets;
  16. import java.security.*;
  17. import java.security.interfaces.RSAPrivateKey;
  18. import java.security.interfaces.RSAPublicKey;
  19. import java.security.spec.PKCS8EncodedKeySpec;
  20. import java.security.spec.X509EncodedKeySpec;
  21. import java.sql.SQLOutput;
  22. public class KeyStoreUtil {
  23. /**
  24. * Java密钥库(Java Key Store,JKS)KEY_STORE
  25. */
  26. public static final String KEY_STORE = "JKS";
  27. public static final String X509 = "X.509";
  28. /**
  29. * keystore基本信息,本示例放在springboot resources目录下。
  30. * @param
  31. */
  32. public static final String keystorePath= KeyStoreUtil.class.getClassLoader().getResource("OEM_Keystore.keystore").getPath();;
  33. private static final String alias = "test";
  34. private static final String storePass = "123456";
  35. private static final String keyPass = "123456";
  36. /**
  37. * 公加私解
  38. * 私加公解
  39. * @throws Exception
  40. */
  41. public static void main(String[] args) throws Exception {
  42. String strPrivateKey = getStrPrivateKey();
  43. String strPublicKey = getStrPublicKey();
  44. // 原始字符串
  45. String message = "我是测试原始内容";
  46. System.out.println("原始数据:"+message);
  47. String messageEn = publicKeyEncrypt(message, strPublicKey);
  48. System.out.println("公钥加密后内容:" + messageEn);
  49. String messageDe = privateKeyDecrypt(messageEn, strPrivateKey);
  50. System.out.println("私钥解密后内容:" + messageDe);
  51. System.out.println("=====================");
  52. //私钥加密,公钥解密
  53. String s = privateKeyEncrypt(message, strPrivateKey);
  54. System.out.println("私钥加密后内容:"+s);
  55. String s1 = publicKeyDecrypt(s, strPublicKey);
  56. System.out.println("公钥解密后内容:"+s1);
  57. }
  58. /**
  59. * BASE64解密
  60. * @param key
  61. * @return
  62. * @throws Exception
  63. */
  64. public static byte[] decryptBASE64(String key) throws Exception {
  65. return(new BASE64Decoder()).decodeBuffer(key);
  66. }
  67. /**
  68. * BASE64加密
  69. * @param key
  70. * @return
  71. * @throws Exception
  72. */
  73. public static String encryptBASE64(byte[] key) throws Exception {
  74. return(new BASE64Encoder()).encodeBuffer(key).replace("\r","").replace("\n","");
  75. }
  76. /**
  77. * 获得KeyStore
  78. *
  79. * @param keyStorePath
  80. * @param password
  81. * @return
  82. * @throws Exception
  83. */
  84. private static KeyStore getKeyStore(String keyStorePath, String password)
  85. throws Exception {
  86. FileInputStream is = new FileInputStream(keyStorePath);
  87. KeyStore ks = KeyStore.getInstance(KEY_STORE);
  88. ks.load(is, password.toCharArray());
  89. is.close();
  90. return ks;
  91. }
  92. /**
  93. * 由KeyStore获得私钥
  94. *
  95. * @param keyStorePath
  96. * @param alias
  97. * @param storePass
  98. * @return
  99. */
  100. private static PrivateKey getPrivateKey(String keyStorePath, String alias, String storePass, String keyPass) throws Exception {
  101. KeyStore ks = getKeyStore(keyStorePath, storePass);
  102. PrivateKey key = (PrivateKey) ks.getKey(alias, keyPass.toCharArray());
  103. return key;
  104. }
  105. /**
  106. * 由Certificate获得公钥
  107. *
  108. * @param keyStorePath KeyStore路径
  109. * @param alias 别名
  110. * @param storePass KeyStore访问密码
  111. */
  112. private static PublicKey getPublicKey(String keyStorePath, String alias, String storePass) throws Exception {
  113. KeyStore ks = getKeyStore(keyStorePath, storePass);
  114. PublicKey key = ks.getCertificate(alias).getPublicKey();
  115. return key;
  116. }
  117. /**
  118. * 从KeyStore中获取公钥,并经BASE64编码
  119. *
  120. */
  121. public static String getStrPublicKey() throws Exception {
  122. PublicKey key = getPublicKey(keystorePath, alias, storePass);
  123. String strKey = encryptBASE64(key.getEncoded());
  124. return strKey;
  125. }
  126. /**
  127. * 获取经BASE64编码后的私钥
  128. *
  129. * @return
  130. * @throws Exception
  131. * @author 奔跑的蜗牛
  132. */
  133. public static String getStrPrivateKey() throws Exception {
  134. PrivateKey key = getPrivateKey(keystorePath, alias, storePass, keyPass);
  135. String strKey = encryptBASE64(key.getEncoded());
  136. return strKey;
  137. }
  138. /**
  139. * RSA公钥加密
  140. *
  141. * @param str 加密字符串
  142. * @param publicKey 公钥
  143. * @return 密文
  144. * @throws Exception 加密过程中的异常信息
  145. */
  146. public static String publicKeyEncrypt(String str, String publicKey) throws Exception {
  147. //base64编码的公钥
  148. byte[] decoded = Base64.decodeBase64(publicKey);
  149. RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").
  150. generatePublic(new X509EncodedKeySpec(decoded));
  151. //RSA加密
  152. Cipher cipher = Cipher.getInstance("RSA");
  153. cipher.init(Cipher.ENCRYPT_MODE, pubKey);
  154. String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
  155. return outStr;
  156. }
  157. /**
  158. * RSA私钥解密
  159. *
  160. * @param str
  161. * @param privateKey 私钥
  162. * @return 铭文
  163. * @throws Exception 解密过程中的异常信息
  164. */
  165. public static String privateKeyDecrypt(String str, String privateKey) throws Exception {
  166. //64位解码加密后的字符串
  167. byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
  168. //base64编码的私钥
  169. byte[] decoded = Base64.decodeBase64(privateKey);
  170. RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
  171. .generatePrivate(new PKCS8EncodedKeySpec(decoded));
  172. //RSA解密
  173. Cipher cipher = Cipher.getInstance("RSA");
  174. cipher.init(Cipher.DECRYPT_MODE, priKey);
  175. String outStr = new String(cipher.doFinal(inputByte), StandardCharsets.UTF_8);
  176. return outStr;
  177. }
  178. /**
  179. * RSA私钥解密
  180. *
  181. * @param bytes
  182. * @param privateKey 私钥
  183. * @return 铭文
  184. * @throws Exception 解密过程中的异常信息
  185. */
  186. public static byte[] privateKeyDecryptBytes(byte[] bytes, String privateKey) throws Exception {
  187. byte[] decoded = Base64.decodeBase64(privateKey);
  188. RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
  189. .generatePrivate(new PKCS8EncodedKeySpec(decoded));
  190. //RSA解密
  191. Cipher cipher = Cipher.getInstance("RSA");
  192. cipher.init(Cipher.DECRYPT_MODE, priKey);
  193. byte[] bytes1 = cipher.doFinal(bytes);
  194. return bytes1;
  195. }
  196. /**
  197. * RSA私钥加密
  198. *
  199. * @param str
  200. * @param privateKey
  201. * @return
  202. * @throws Exception
  203. */
  204. public static String privateKeyEncrypt(String str, String privateKey) throws Exception {
  205. //base64编码的公钥
  206. byte[] decoded = Base64.decodeBase64(privateKey);
  207. PrivateKey priKey = KeyFactory.getInstance("RSA").
  208. generatePrivate(new PKCS8EncodedKeySpec(decoded));
  209. //RSA加密
  210. Cipher cipher = Cipher.getInstance("RSA");
  211. cipher.init(Cipher.ENCRYPT_MODE, priKey);
  212. String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes()));
  213. return outStr;
  214. }
  215. /**
  216. * RSA公钥解密
  217. *
  218. * @param str
  219. * @param publicKey
  220. * @return
  221. * @throws Exception
  222. */
  223. public static String publicKeyDecrypt(String str, String publicKey) throws Exception {
  224. //64位解码加密后的字符串
  225. byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
  226. //base64编码的私钥
  227. byte[] decoded = Base64.decodeBase64(publicKey);
  228. PublicKey pubKey = KeyFactory.getInstance("RSA")
  229. .generatePublic(new X509EncodedKeySpec(decoded));
  230. //RSA解密
  231. Cipher cipher = Cipher.getInstance("RSA");
  232. cipher.init(Cipher.DECRYPT_MODE, pubKey);
  233. String outStr = new String(cipher.doFinal(inputByte));
  234. return outStr;
  235. }
  236. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/742026
推荐阅读
相关标签
  

闽ICP备14008679号