RSA加密/解密工具类

我就是我 2024-03-23 16:40 177阅读 0赞
  1. import java.io.ByteArrayOutputStream;
  2. import java.security.KeyFactory;
  3. import java.security.KeyPair;
  4. import java.security.KeyPairGenerator;
  5. import java.security.PrivateKey;
  6. import java.security.PublicKey;
  7. import java.security.Signature;
  8. import java.security.spec.PKCS8EncodedKeySpec;
  9. import java.security.spec.X509EncodedKeySpec;
  10. import javax.crypto.Cipher;
  11. import org.apache.commons.codec.binary.Base64;
  12. public class TestRSA {
  13. /**
  14. * RSA最大加密明文大小
  15. */
  16. private static final int MAX_ENCRYPT_BLOCK = 117;
  17. /**
  18. * RSA最大解密密文大小
  19. */
  20. private static final int MAX_DECRYPT_BLOCK = 128;
  21. /**
  22. * 获取密钥对
  23. *
  24. * @return 密钥对
  25. */
  26. public static KeyPair getKeyPair() throws Exception {
  27. KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
  28. generator.initialize(1024);
  29. return generator.generateKeyPair();
  30. }
  31. /**
  32. * 获取私钥
  33. *
  34. * @param privateKey 私钥字符串
  35. * @return
  36. */
  37. public static PrivateKey getPrivateKey(String privateKey) throws Exception {
  38. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  39. byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
  40. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
  41. return keyFactory.generatePrivate(keySpec);
  42. }
  43. /**
  44. * 获取公钥
  45. *
  46. * @param publicKey 公钥字符串
  47. * @return
  48. */
  49. public static PublicKey getPublicKey(String publicKey) throws Exception {
  50. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  51. byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
  52. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
  53. return keyFactory.generatePublic(keySpec);
  54. }
  55. /**
  56. * RSA加密
  57. *
  58. * @param data 待加密数据
  59. * @param publicKey 公钥
  60. * @return
  61. */
  62. public static String encrypt(String data, PublicKey publicKey) throws Exception {
  63. Cipher cipher = Cipher.getInstance("RSA");
  64. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  65. int inputLen = data.getBytes().length;
  66. ByteArrayOutputStream out = new ByteArrayOutputStream();
  67. int offset = 0;
  68. byte[] cache;
  69. int i = 0;
  70. // 对数据分段加密
  71. while (inputLen - offset > 0) {
  72. if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
  73. cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
  74. } else {
  75. cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
  76. }
  77. out.write(cache, 0, cache.length);
  78. i++;
  79. offset = i * MAX_ENCRYPT_BLOCK;
  80. }
  81. byte[] encryptedData = out.toByteArray();
  82. out.close();
  83. // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
  84. // 加密后的字符串
  85. return new String(Base64.encodeBase64String(encryptedData));
  86. }
  87. /**
  88. * RSA解密
  89. *
  90. * @param data 待解密数据
  91. * @param privateKey 私钥
  92. * @return
  93. */
  94. public static String decrypt(String data, PrivateKey privateKey) throws Exception {
  95. Cipher cipher = Cipher.getInstance("RSA");
  96. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  97. byte[] dataBytes = Base64.decodeBase64(data);
  98. int inputLen = dataBytes.length;
  99. ByteArrayOutputStream out = new ByteArrayOutputStream();
  100. int offset = 0;
  101. byte[] cache;
  102. int i = 0;
  103. // 对数据分段解密
  104. while (inputLen - offset > 0) {
  105. if (inputLen - offset > MAX_DECRYPT_BLOCK) {
  106. cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
  107. } else {
  108. cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
  109. }
  110. out.write(cache, 0, cache.length);
  111. i++;
  112. offset = i * MAX_DECRYPT_BLOCK;
  113. }
  114. byte[] decryptedData = out.toByteArray();
  115. out.close();
  116. // 解密后的内容
  117. return new String(decryptedData, "UTF-8");
  118. }
  119. /**
  120. * 签名
  121. *
  122. * @param data 待签名数据
  123. * @param privateKey 私钥
  124. * @return 签名
  125. */
  126. public static String sign(String data, PrivateKey privateKey) throws Exception {
  127. byte[] keyBytes = privateKey.getEncoded();
  128. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
  129. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  130. PrivateKey key = keyFactory.generatePrivate(keySpec);
  131. Signature signature = Signature.getInstance("MD5withRSA");
  132. signature.initSign(key);
  133. signature.update(data.getBytes());
  134. return new String(Base64.encodeBase64(signature.sign()));
  135. }
  136. /**
  137. * 验签
  138. *
  139. * @param srcData 原始字符串
  140. * @param publicKey 公钥
  141. * @param sign 签名
  142. * @return 是否验签通过
  143. */
  144. public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
  145. byte[] keyBytes = publicKey.getEncoded();
  146. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
  147. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  148. PublicKey key = keyFactory.generatePublic(keySpec);
  149. Signature signature = Signature.getInstance("MD5withRSA");
  150. signature.initVerify(key);
  151. signature.update(srcData.getBytes());
  152. return signature.verify(Base64.decodeBase64(sign.getBytes()));
  153. }
  154. public static void main(String[] args) {
  155. try {
  156. // 生成密钥对
  157. KeyPair keyPair = getKeyPair();
  158. String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
  159. String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
  160. System.out.println("私钥:" + privateKey);
  161. System.out.println("公钥:" + publicKey);
  162. // RSA加密
  163. String data = "待加密的文字内容";
  164. String encryptData = encrypt(data, getPublicKey(publicKey));
  165. System.out.println("加密后内容:" + encryptData);
  166. // RSA解密
  167. String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
  168. System.out.println("解密后内容:" + decryptData);
  169. // RSA签名
  170. String sign = sign(data, getPrivateKey(privateKey));
  171. // RSA验签
  172. boolean result = verify(data, getPublicKey(publicKey), sign);
  173. System.out.print("验签结果:" + result);
  174. } catch (Exception e) {
  175. e.printStackTrace();
  176. System.out.print("加解密异常");
  177. }
  178. }
  179. }

发表评论

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

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

相关阅读

    相关 RSA加密解密

    RSA加密与解密 RSA算法的密钥由公钥和私钥组成,公钥用于加密,私钥用于解密。顾名思义,公钥就是可以进行公开的密钥,一般可以公开给你的合作伙伴;私钥就是私有的,也就是只

    相关 JS-RSA加密解密

      在上一篇文章《Java使用RSA加密解密签名及校验》中,用java实现加密解密,但是在实际应用中,如前端页面用户输入的密码传输给后台服务前,需加密,也就是公钥加密,私钥解密