java RSA公钥加密私钥解密

Myth丶恋晨 2021-12-23 15:39 501阅读 0赞

RSA非对称加密原理此处不是重点,麻烦读者自行了解哦。如果了解了RSA,你就知道为什么要用公钥加密,私钥解密(不懂私聊哦),下面是RSA加解密例子,RSA加解密算法有好多种,这是常见也是比较简单的一种。

  1. package com.alipay;
  2. import cn.paypalm.commons.util.Logger;
  3. import cn.paypalm.commons.util.LoggerFactory;
  4. import org.apache.commons.codec.binary.Base64;
  5. import javax.crypto.Cipher;
  6. import java.io.BufferedReader;
  7. import java.io.ByteArrayOutputStream;
  8. import java.io.InputStream;
  9. import java.io.InputStreamReader;
  10. import java.security.KeyFactory;
  11. import java.security.PrivateKey;
  12. import java.security.PublicKey;
  13. import java.security.cert.CertificateFactory;
  14. import java.security.spec.PKCS8EncodedKeySpec;
  15. import java.security.spec.X509EncodedKeySpec;
  16. /**
  17. * Created by lifeng on 2019/6/25.
  18. */
  19. public class RSAUtil {
  20. private static final Logger LOGGER= LoggerFactory.getLogger(RSAUtil.class);
  21. /**
  22. * RSA最大加密明文大小
  23. */
  24. private static final int MAX_ENCRYPT_BLOCK = 117;
  25. /**
  26. * RSA最大解密密文大小(如果秘钥是1024bit,解密最大块是128,如果秘钥是2048bit,解密最大块是256)
  27. */
  28. private static final int MAX_DECRYPT_BLOCK = 128;
  29. private static PrivateKey globalPrivateKey = null;
  30. private static PublicKey globalPublicKey = null;
  31. public static PrivateKey getPrivateKey(String prikeypath) throws Exception {
  32. if(globalPrivateKey != null){
  33. return globalPrivateKey;
  34. }
  35. InputStream in = RSAUtil.class.getClassLoader().getResourceAsStream(prikeypath);
  36. BufferedReader br = new BufferedReader(new InputStreamReader(in));
  37. StringBuilder sb = new StringBuilder();
  38. String readLine = null;
  39. while((readLine = br.readLine()) != null) {
  40. if(readLine.charAt(0) != 45) {
  41. sb.append(readLine);
  42. sb.append('\r');
  43. }
  44. }
  45. in.close();
  46. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(sb.toString()));
  47. try {
  48. KeyFactory factory = KeyFactory.getInstance("RSA");
  49. PrivateKey privateKey = factory.generatePrivate(pkcs8EncodedKeySpec);
  50. globalPrivateKey = privateKey;
  51. return globalPrivateKey;
  52. } catch (Exception e) {
  53. LOGGER.error("获取私钥异常",e);
  54. throw e;
  55. }
  56. }
  57. public static PublicKey getPublicByPublic(String keypath) throws Exception {
  58. if(globalPublicKey != null){
  59. return globalPublicKey;
  60. }
  61. InputStream in = RSAUtil.class.getClassLoader().getResourceAsStream(keypath);
  62. BufferedReader br = new BufferedReader(new InputStreamReader(in));
  63. StringBuilder sb = new StringBuilder();
  64. String readLine = null;
  65. while((readLine = br.readLine()) != null) {
  66. if(readLine.charAt(0) != 45) {
  67. sb.append(readLine);
  68. sb.append('\r');
  69. }
  70. }
  71. in.close();
  72. CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  73. X509EncodedKeySpec ks = new X509EncodedKeySpec(Base64.decodeBase64(sb.toString()));
  74. KeyFactory kf = KeyFactory.getInstance("RSA");
  75. globalPublicKey = kf.generatePublic(ks);
  76. return globalPublicKey;
  77. }
  78. public static String dencrypt(String str,String privateKeyStr) throws Exception{
  79. //64位解码加密后的字符串
  80. byte[] encryptedData = Base64.decodeBase64(str.getBytes("UTF-8"));
  81. PrivateKey privateKey = getPrivateKey(privateKeyStr);
  82. //RSA加密
  83. Cipher cipher = Cipher.getInstance("RSA");
  84. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  85. int inputLen = encryptedData.length;
  86. ByteArrayOutputStream out = new ByteArrayOutputStream();
  87. int offSet = 0;
  88. byte[] cache;
  89. int i = 0;
  90. // 对数据分段解密
  91. while (inputLen - offSet > 0) {
  92. if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
  93. cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
  94. } else {
  95. cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
  96. }
  97. out.write(cache, 0, cache.length);
  98. i++;
  99. offSet = i * MAX_DECRYPT_BLOCK;
  100. }
  101. byte[] decryptedData = out.toByteArray();
  102. out.close();
  103. String outStr = new String(decryptedData,"UTF-8");
  104. return outStr;
  105. }
  106. public static String encrypt(String data, String publicKeyPath) throws Exception{
  107. PublicKey pubKey = getPublicByPublic(publicKeyPath);
  108. //RSA加密
  109. Cipher cipher = Cipher.getInstance("RSA");
  110. cipher.init(Cipher.ENCRYPT_MODE, pubKey);
  111. byte[] dataByte = data.getBytes("UTF-8");
  112. int inputLen = dataByte.length;
  113. ByteArrayOutputStream out = new ByteArrayOutputStream();
  114. int offSet = 0;
  115. byte[] cache;
  116. int i = 0;
  117. // 对数据分段加密
  118. while (inputLen - offSet > 0) {
  119. if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
  120. cache = cipher.doFinal(dataByte, offSet, MAX_ENCRYPT_BLOCK);
  121. } else {
  122. cache = cipher.doFinal(dataByte, offSet, inputLen - offSet);
  123. }
  124. out.write(cache, 0, cache.length);
  125. i++;
  126. offSet = i * MAX_ENCRYPT_BLOCK;
  127. }
  128. byte[] encryptedData = out.toByteArray();
  129. out.close();
  130. String outStr = Base64.encodeBase64String(encryptedData);
  131. return outStr;
  132. }
  133. public static void main(String[] args) throws Exception {
  134. //现在生成公私钥对,http://web.chacuo.net/netrsakeypair
  135. String data = "我是打酱油的";
  136. //使用公钥加密,第二个参数classpath下的公钥文件
  137. data = encrypt(data,"public1024.key");
  138. System.out.println("加密后的数据:"+data);
  139. //使用私钥解密,第二个参数classpath下的私钥文件
  140. data = dencrypt(data,"private1024.key");
  141. System.out.println("解密后的数据:"+data);
  142. }
  143. }

" class="reference-link">生成公私钥对,http://web.chacuo.net/netrsakeypair 在这里插入图片描述

同时给你读者推荐一个好用在线加解密的网站,你会喜欢的。
http://tool.chacuo.net/cryptdes
http://encode.chahuo.com/

发表评论

表情:
评论列表 (有 0 条评论,501人围观)

还没有评论,来说两句吧...

相关阅读