当前位置:   article > 正文

在Java下进行RSA加密(私钥加密,公钥解密)_data must not be longer than 245 bytes

data must not be longer than 245 bytes

加密过长的会报错:

Data must not be longer than 245 bytes

原因是应为不同长度的密钥对应可以加密不同最大长度的原文,2048就对应245

解决办法是:

方案一: 分段

方案二: RSA加密是有长度限制的.单纯用RSA加密较长数据时得使用分段加密,效率低下.用RSA+AES是比较主流的做法:AES加密数据产生密文,RSA加密AES密钥产生加密后的AES密钥,然后将密文和加密后的AES密钥一起传输:https://blog.csdn.net/huang007guo/article/details/104639490

  1. package com.wjj.application.paysdk.crypt.tools;
  2. import org.bouncycastle.crypto.InvalidCipherTextException;
  3. import javax.crypto.BadPaddingException;
  4. import javax.crypto.Cipher;
  5. import javax.crypto.IllegalBlockSizeException;
  6. import javax.crypto.NoSuchPaddingException;
  7. import java.io.File;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10. import java.io.UnsupportedEncodingException;
  11. import java.security.*;
  12. import java.security.spec.InvalidKeySpecException;
  13. import java.security.spec.PKCS8EncodedKeySpec;
  14. import java.security.spec.X509EncodedKeySpec;
  15. import java.util.Base64;
  16. /**
  17. * RSA 加密工具 参考:https://www.devglan.com/java8/rsa-encryption-decryption-java
  18. * 加密过长的会报错:
  19. Data must not be longer than 245 bytes
  20. 原因是应为不同长度的密钥对应可以加密不同最大长度的原文,2048就对应245
  21. 解决办法是:
  22. 1.分段
  23. 2.RSA加密是有长度限制的.单纯用RSA加密较长数据时得使用分段加密,效率低下.用RSA+AES是比较主流的做法:AES加密数据产生密文,RSA加密AES密钥产生加密后的AES密钥,然后将密文和加密后的AES密钥一起传输
  24. * @author hank
  25. * @since 2020/2/28 0028 下午 15:42
  26. */
  27. public class RsaCryptTools {
  28. private static final String CHARSET = "utf-8";
  29. private static final Base64.Decoder decoder64 = Base64.getDecoder();
  30. private static final Base64.Encoder encoder64 = Base64.getEncoder();
  31. /**
  32. * 生成公私钥
  33. * @param keySize
  34. * @return
  35. * @throws NoSuchAlgorithmException
  36. */
  37. public static SecretKey generateSecretKey(int keySize) throws NoSuchAlgorithmException {
  38. //生成密钥对
  39. KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  40. keyGen.initialize(keySize, new SecureRandom());
  41. KeyPair pair = keyGen.generateKeyPair();
  42. PrivateKey privateKey = pair.getPrivate();
  43. PublicKey publicKey = pair.getPublic();
  44. //这里可以将密钥对保存到本地
  45. return new SecretKey(encoder64.encodeToString(publicKey.getEncoded()), encoder64.encodeToString(privateKey.getEncoded()));
  46. }
  47. /**
  48. * 私钥加密
  49. * @param data
  50. * @param privateInfoStr
  51. * @return
  52. * @throws IOException
  53. * @throws InvalidCipherTextException
  54. */
  55. public static String encryptData(String data, String privateInfoStr) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
  56. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  57. cipher.init(Cipher.ENCRYPT_MODE, getPrivateKey(privateInfoStr));
  58. return encoder64.encodeToString(cipher.doFinal(data.getBytes(CHARSET)));
  59. }
  60. /**
  61. * 公钥解密
  62. * @param data
  63. * @param publicInfoStr
  64. * @return
  65. */
  66. public static String decryptData(String data, String publicInfoStr) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
  67. byte[] encryptDataBytes=decoder64.decode(data.getBytes(CHARSET));
  68. //解密
  69. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  70. cipher.init(Cipher.DECRYPT_MODE, getPublicKey(publicInfoStr));
  71. return new String(cipher.doFinal(encryptDataBytes), CHARSET);
  72. }
  73. private static PublicKey getPublicKey(String base64PublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
  74. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()));
  75. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  76. return keyFactory.generatePublic(keySpec);
  77. }
  78. private static PrivateKey getPrivateKey(String base64PrivateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
  79. PrivateKey privateKey = null;
  80. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes()));
  81. KeyFactory keyFactory = null;
  82. keyFactory = KeyFactory.getInstance("RSA");
  83. privateKey = keyFactory.generatePrivate(keySpec);
  84. return privateKey;
  85. }
  86. /**
  87. * 密钥实体
  88. * @author hank
  89. * @since 2020/2/28 0028 下午 16:27
  90. */
  91. public static class SecretKey {
  92. /**
  93. * 公钥
  94. */
  95. private String publicKey;
  96. /**
  97. * 私钥
  98. */
  99. private String privateKey;
  100. public SecretKey(String publicKey, String privateKey) {
  101. this.publicKey = publicKey;
  102. this.privateKey = privateKey;
  103. }
  104. public String getPublicKey() {
  105. return publicKey;
  106. }
  107. public void setPublicKey(String publicKey) {
  108. this.publicKey = publicKey;
  109. }
  110. public String getPrivateKey() {
  111. return privateKey;
  112. }
  113. public void setPrivateKey(String privateKey) {
  114. this.privateKey = privateKey;
  115. }
  116. @Override
  117. public String toString() {
  118. return "SecretKey{" +
  119. "publicKey='" + publicKey + '\'' +
  120. ", privateKey='" + privateKey + '\'' +
  121. '}';
  122. }
  123. }
  124. private static void writeToFile(String path, byte[] key) throws IOException {
  125. File f = new File(path);
  126. f.getParentFile().mkdirs();
  127. try(FileOutputStream fos = new FileOutputStream(f)) {
  128. fos.write(key);
  129. fos.flush();
  130. }
  131. }
  132. public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, InvalidKeySpecException {
  133. SecretKey secretKey = generateSecretKey(2048);
  134. System.out.println(secretKey);
  135. String enStr = encryptData("你好测试测试", secretKey.getPrivateKey());
  136. System.out.println(enStr);
  137. String deStr = decryptData(enStr, secretKey.getPublicKey());
  138. System.out.println(deStr);
  139. enStr = encryptData("你好测试测试hello", secretKey.getPrivateKey());
  140. System.out.println(enStr);
  141. deStr = decryptData(enStr, secretKey.getPublicKey());
  142. System.out.println(deStr);
  143. }
  144. }

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

闽ICP备14008679号