java rsa 解密报:javax.crypto.BadPaddingException: Decryption error

Exception in thread “main” javax.crypto.BadPaddingException: Decryption error

    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)

    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)

    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)

    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)

    at javax.crypto.Cipher.doFinal(Cipher.java:2223)

    at com.asymmetric.rsa.TestRSA.testDecrypt(TestRSA.java:115)

    at com.asymmetric.rsa.TestRSA.main(TestRSA.java:34)

简单解释:

字面意思就是解密的时候填充错误,rsa 加解密都是把数据必须满足一定的长度,如果  不满足就要进行填充(一般是补0)直到满足特定的长度

测试代码


   
  
  1. package com.asymmetric.rsa;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.security.InvalidKeyException;
  5. import java.security.KeyFactory;
  6. import java.security.NoSuchAlgorithmException;
  7. import java.security.PrivateKey;
  8. import java.security.PublicKey;
  9. import java.security.spec.InvalidKeySpecException;
  10. import java.security.spec.PKCS8EncodedKeySpec;
  11. import java.security.spec.X509EncodedKeySpec;
  12. import java.util.Base64;
  13. import javax.crypto.BadPaddingException;
  14. import javax.crypto.Cipher;
  15. import javax.crypto.IllegalBlockSizeException;
  16. import javax.crypto.NoSuchPaddingException;
  17. public class TestRSA {
  18. public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQgEoj3z9JrdPNI23DbMQkl3gkGuDke7iBr5yrYyqolkTyxuBLWFwHNuGv4VKOj9fXg61QxpaJ/fxDBvMvmkBSRowHBloGFceVTx8wV/8u0DcjvTCu0IZ1zp6wjG6xBn5j66Sg/q+9hvaY2p7fkKmsvcW6VoNPgQHU1Cf01DLZmQIDAQAB+oXcINOiE3AsuZ4VJmwNZg9Y/7fY+OFRS2JAh5YMsrv2qyoGP+Z9ksre26NYR+Lt91B2lhdwJHLpQpziaANZm/ONb31fj/lwIDAQAB";
  19. public static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANCASiPfP0mt080jbcNsxCSXeCQa4OR7uIGvnKtjKqiWRPLG4EtYXAc24a/hUo6P19eDrVDGlon9/EMG8y+aQFJGjAcGWgYVx5VPHzBX/y7QNyO9MK7QhnXOnrCMbrEGfmPrpKD+r72G9pjant+Qqay9xbpWg0+BAdTUJ/TUMtmZAgMBAAECgYBSozY/Z4FW+31h5fPgK+DFu/8TGFAgXuTvCaJnz2Md9IkZTDejxT6cYWUr53toI5zhvz/XLw6FXNQ54KxMJq/s9PiZYUgq/PMrnyU4gBSTm5BmiWjdaGicVEZ1lofHjpkAchPNW/CzwxD8AeKI7QaObE+EkWbLAi6sa+nRdHKgrQJBAOwYLD2DncU15XCKS0RNzTrNohdBQcisOPHdtQO0CGZlxx3xjuU4WL6/EpdmbjTeYbOSDKCmY5vyVbYZdOWfEs8CQQDiFIwWpvW2WLxLVw3i2P55WmMMXuecwEzg++ae3Ht7nW0zNcWSsyvHh40sM8XqEzmWOzMY6JOePbkuVfWTc4cXAkBRzf5mQhiEoKwjVofF3v9hhKbJT/8vPR1uENgLtHHEqTdZFL3ihqeZUDNs6jz9bKCFy/E8KOsSueEg+6kZdwjZAkEAj2RW4fstd2VasDJb5ViaNqAEmJENOBej60L6KCJR07qqy0M8t+oaR2iLOtDvo6Jj8QxFQXQqRMCDVodAxjANKwJAL3KuaqA6kdy9RxdV3uP8nRXLY7C/1ZIK6U0pyZqKXEwpD+7Ar3hwwhPz9TeuoqjB/cCknZjw70BQFQ0/VUHW2g==";
  20. private static String algorithm = "RSA"; //$NON-NLS-1$
  21. private static final int MAX_ENCRYPT_BLOCK = 117;
  22. private static final int MAX_DECRYPT_BLOCK = 128;
  23. private static String data = "test jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihg"; //$NON-NLS-1$
  24. public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException {
  25. String test = testEncrypt(privateKey,data);
  26. String testDecrypt = testDecrypt(publicKey, test);
  27. System.out.println(testDecrypt);
  28. }
  29. /**
  30. * 加密
  31. * @param key
  32. * @param data
  33. * @return
  34. * @throws NoSuchAlgorithmException
  35. * @throws InvalidKeySpecException
  36. * @throws NoSuchPaddingException
  37. * @throws IllegalBlockSizeException
  38. * @throws BadPaddingException
  39. * @throws InvalidKeyException
  40. * @throws IOException
  41. */
  42. public static String testEncrypt(String key,String data) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException{
  43. byte[] decode = Base64.getDecoder().decode(key);
  44. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode);
  45. KeyFactory kf = KeyFactory.getInstance(algorithm);
  46. PrivateKey generatePrivate = kf.generatePrivate(pkcs8EncodedKeySpec);
  47. Cipher ci = Cipher.getInstance(algorithm);
  48. ci.init(Cipher.ENCRYPT_MODE, generatePrivate);
  49. byte[] bytes = data.getBytes();
  50. int inputLen = bytes.length;
  51. int offLen = 0; //偏移量
  52. int i = 0;
  53. ByteArrayOutputStream bops = new ByteArrayOutputStream();
  54. while(inputLen - offLen > 0){
  55. byte [] cache;
  56. if(inputLen - offLen > 117){
  57. cache = ci.doFinal(bytes, offLen, 117);
  58. } else{
  59. cache = ci.doFinal(bytes, offLen,inputLen - offLen);
  60. }
  61. bops.write(cache);
  62. i++;
  63. offLen = 117 * i;
  64. }
  65. bops.close();
  66. byte[] encryptedData = bops.toByteArray();
  67. String encodeToString = Base64.getEncoder().encodeToString(encryptedData);
  68. return encodeToString;
  69. }
  70. /**
  71. * 解密
  72. * @param key
  73. * @param data
  74. * @return
  75. * @throws NoSuchAlgorithmException
  76. * @throws InvalidKeyException
  77. * @throws NoSuchPaddingException
  78. * @throws InvalidKeySpecException
  79. * @throws BadPaddingException
  80. * @throws IllegalBlockSizeException
  81. * @throws IOException
  82. */
  83. public static String testDecrypt(String key,String data) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, IOException{
  84. byte[] decode = Base64.getDecoder().decode(key);
  85. // PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode); //java底层 RSA公钥只支持X509EncodedKeySpec这种格式
  86. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decode);
  87. KeyFactory kf = KeyFactory.getInstance(algorithm);
  88. PublicKey generatePublic = kf.generatePublic(x509EncodedKeySpec);
  89. Cipher ci = Cipher.getInstance(algorithm);
  90. ci.init(Cipher.DECRYPT_MODE,generatePublic);
  91. int inputLen = data.getBytes().length;
  92. byte[] bytes = data.getBytes();
  93. int offLen = 0;
  94. int i = 0;
  95. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  96. while(inputLen - offLen > 0){
  97. byte[] cache;
  98. if(inputLen - offLen > 128){
  99. cache = ci.doFinal(bytes,offLen, 128);
  100. } else{
  101. cache = ci.doFinal(bytes,offLen,inputLen - offLen);
  102. }
  103. byteArrayOutputStream.write(cache);
  104. i++;
  105. offLen = 128 * i;
  106. }
  107. byteArrayOutputStream.close();
  108. byte[] byteArray = byteArrayOutputStream.toByteArray();
  109. return new String(byteArray);
  110. }
  111. }

问题点:

后来发现确实是我自己的错误,rsa 加密后返回的字符串使用Base64编码的,忘了解密直接getBytes()就出错了

api 指出:BadPaddingException – 如果此 Cipher 为解密模式,并且未请求填充(或不填充),但解密的数据没有用适当的填充字节进行限制

只要是cipher.doFinal()解密时报 BadPaddingException 肯定是传入的字节数组有问题,传的不是加密时生成的数组

修正后的代码:


   
  
  1. package com.asymmetric.rsa;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.security.InvalidKeyException;
  5. import java.security.KeyFactory;
  6. import java.security.NoSuchAlgorithmException;
  7. import java.security.PrivateKey;
  8. import java.security.PublicKey;
  9. import java.security.spec.InvalidKeySpecException;
  10. import java.security.spec.PKCS8EncodedKeySpec;
  11. import java.security.spec.X509EncodedKeySpec;
  12. import java.util.Base64;
  13. import javax.crypto.BadPaddingException;
  14. import javax.crypto.Cipher;
  15. import javax.crypto.IllegalBlockSizeException;
  16. import javax.crypto.NoSuchPaddingException;
  17. public class TestRSA {
  18. public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQgEoj3z9JrdPNI23DbMQkl3gkGuDke7iBr5yrYyqolkTyxuBLWFwHNuGv4VKOj9fXg61QxpaJ/fxDBvMvmkBSRowHBloGFceVTx8wV/8u0DcjvTCu0IZ1zp6wjG6xBn5j66Sg/q+9hvaY2p7fkKmsvcW6VoNPgQHU1Cf01DLZmQIDAQAB+oXcINOiE3AsuZ4VJmwNZg9Y/7fY+OFRS2JAh5YMsrv2qyoGP+Z9ksre26NYR+Lt91B2lhdwJHLpQpziaANZm/ONb31fj/lwIDAQAB";
  19. public static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANCASiPfP0mt080jbcNsxCSXeCQa4OR7uIGvnKtjKqiWRPLG4EtYXAc24a/hUo6P19eDrVDGlon9/EMG8y+aQFJGjAcGWgYVx5VPHzBX/y7QNyO9MK7QhnXOnrCMbrEGfmPrpKD+r72G9pjant+Qqay9xbpWg0+BAdTUJ/TUMtmZAgMBAAECgYBSozY/Z4FW+31h5fPgK+DFu/8TGFAgXuTvCaJnz2Md9IkZTDejxT6cYWUr53toI5zhvz/XLw6FXNQ54KxMJq/s9PiZYUgq/PMrnyU4gBSTm5BmiWjdaGicVEZ1lofHjpkAchPNW/CzwxD8AeKI7QaObE+EkWbLAi6sa+nRdHKgrQJBAOwYLD2DncU15XCKS0RNzTrNohdBQcisOPHdtQO0CGZlxx3xjuU4WL6/EpdmbjTeYbOSDKCmY5vyVbYZdOWfEs8CQQDiFIwWpvW2WLxLVw3i2P55WmMMXuecwEzg++ae3Ht7nW0zNcWSsyvHh40sM8XqEzmWOzMY6JOePbkuVfWTc4cXAkBRzf5mQhiEoKwjVofF3v9hhKbJT/8vPR1uENgLtHHEqTdZFL3ihqeZUDNs6jz9bKCFy/E8KOsSueEg+6kZdwjZAkEAj2RW4fstd2VasDJb5ViaNqAEmJENOBej60L6KCJR07qqy0M8t+oaR2iLOtDvo6Jj8QxFQXQqRMCDVodAxjANKwJAL3KuaqA6kdy9RxdV3uP8nRXLY7C/1ZIK6U0pyZqKXEwpD+7Ar3hwwhPz9TeuoqjB/cCknZjw70BQFQ0/VUHW2g==";
  20. private static String algorithm = "RSA"; //$NON-NLS-1$
  21. private static final int MAX_ENCRYPT_BLOCK = 117;
  22. private static final int MAX_DECRYPT_BLOCK = 128;
  23. private static String data = "test jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihg"; //$NON-NLS-1$
  24. public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException {
  25. String test = testEncrypt(privateKey,data);
  26. String testDecrypt = testDecrypt(publicKey, test);
  27. System.out.println(testDecrypt);
  28. }
  29. /**
  30. * 加密
  31. * @param key
  32. * @param data
  33. * @return
  34. * @throws NoSuchAlgorithmException
  35. * @throws InvalidKeySpecException
  36. * @throws NoSuchPaddingException
  37. * @throws IllegalBlockSizeException
  38. * @throws BadPaddingException
  39. * @throws InvalidKeyException
  40. * @throws IOException
  41. */
  42. public static String testEncrypt(String key,String data) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException{
  43. byte[] decode = Base64.getDecoder().decode(key);
  44. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode);
  45. KeyFactory kf = KeyFactory.getInstance(algorithm);
  46. PrivateKey generatePrivate = kf.generatePrivate(pkcs8EncodedKeySpec);
  47. Cipher ci = Cipher.getInstance(algorithm);
  48. ci.init(Cipher.ENCRYPT_MODE, generatePrivate);
  49. byte[] bytes = data.getBytes();
  50. int inputLen = bytes.length;
  51. int offLen = 0; //偏移量
  52. int i = 0;
  53. ByteArrayOutputStream bops = new ByteArrayOutputStream();
  54. while(inputLen - offLen > 0){
  55. byte [] cache;
  56. if(inputLen - offLen > 117){
  57. cache = ci.doFinal(bytes, offLen, 117);
  58. } else{
  59. cache = ci.doFinal(bytes, offLen,inputLen - offLen);
  60. }
  61. bops.write(cache);
  62. i++;
  63. offLen = 117 * i;
  64. }
  65. bops.close();
  66. byte[] encryptedData = bops.toByteArray();
  67. String encodeToString = Base64.getEncoder().encodeToString(encryptedData);
  68. return encodeToString;
  69. }
  70. /**
  71. * 解密
  72. * @param key
  73. * @param data
  74. * @return
  75. * @throws NoSuchAlgorithmException
  76. * @throws InvalidKeyException
  77. * @throws NoSuchPaddingException
  78. * @throws InvalidKeySpecException
  79. * @throws BadPaddingException
  80. * @throws IllegalBlockSizeException
  81. * @throws IOException
  82. */
  83. public static String testDecrypt(String key,String data) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, IOException{
  84. byte[] decode = Base64.getDecoder().decode(key);
  85. // PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode); //java底层 RSA公钥只支持X509EncodedKeySpec这种格式
  86. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decode);
  87. KeyFactory kf = KeyFactory.getInstance(algorithm);
  88. PublicKey generatePublic = kf.generatePublic(x509EncodedKeySpec);
  89. Cipher ci = Cipher.getInstance(algorithm);
  90. ci.init(Cipher.DECRYPT_MODE,generatePublic);
  91. byte[] bytes = Base64.getDecoder().decode(data);
  92. int inputLen = bytes.length;
  93. int offLen = 0;
  94. int i = 0;
  95. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  96. while(inputLen - offLen > 0){
  97. byte[] cache;
  98. if(inputLen - offLen > 128){
  99. cache = ci.doFinal(bytes,offLen, 128);
  100. } else{
  101. cache = ci.doFinal(bytes,offLen,inputLen - offLen);
  102. }
  103. byteArrayOutputStream.write(cache);
  104. i++;
  105. offLen = 128 * i;
  106. }
  107. byteArrayOutputStream.close();
  108. byte[] byteArray = byteArrayOutputStream.toByteArray();
  109. return new String(byteArray);
  110. }
  111. }

    原文作者:星朝
    原文地址: https://www.cnblogs.com/jpfss/p/10203164.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞