天天看點

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)直到滿足特定的長度

測試代碼

問題點:

後來發現确實是我自己的錯誤,rsa 加密後傳回的字元串使用Base64編碼的,忘了解密直接getBytes()就出錯了

api 指出:​<code>​BadPaddingException​</code>​ - 如果此 Cipher 為解密模式,并且未請求填充(或不填充),但解密的資料沒有用适當的填充位元組進行限制

隻要是cipher.doFinal()解密時報 ​<code>​BadPaddingException​</code>​ 肯定是傳入的位元組數組有問題,傳的不是加密時生成的數組

修正後的代碼: