开发者

Getting 'BadPaddingException: pad block corrupted' in AES/CBC/PKCS5Padding

My constants

 public static final String AES_ALGORITHM_MODE_PADDING = "AES/CBC/PKCS5Padding";
 public static final String AES = "AES";
 public static final String PROVIDER = "BC";

Encryption

   Cipher aesCipher = Cipher.getInstance(AES_ALGORITHM_MODE_PADDING, PROVIDER);
   SecretKeySpec aeskeySpec = new SecretKeySpec(rawAesKey, AES);
   aesCipher.init(Cipher.ENCRYPT_MODE, aeskeySpec);
   byte[] encryptedData = aesC开发者_运维百科ipher.doFinal(data);
   this.iv = Base64.encodeBase64(aesCipher.getIV()); //get hold of the random IV

   return encryptedData;

In another class I do Decryption

      IvParameterSpec ivspec = new IvParameterSpec(this.iv); //this is already been converted from base64 to raw form.

Cipher aesCipher = Cipher.getInstance(AES_ALGORITHM_MODE_PADDING, PROVIDER);
SecretKeySpec aeskeySpec = new SecretKeySpec(rawAesKey, AES);
aesCipher.init(Cipher.DECRYPT_MODE, aeskeySpec, ivspec);

return aesCipher.doFinal(rawEncryptedLicenseData);

Now when I run this I get a BadPaddingException at doFinal when decrypting, what am I doing wrong? If I remove the CBC/PKCS5Padding and IV stuff and just use AES, it works!


You can try CTR mode with no padding:

Cipher cipherAlg = Cipher.getInstance("AES/CTR/NoPadding", PROVIDER);
byte[] ivBytes = new byte[cipherAlg.getBlockSize()];
(new SecureRandom()).nextBytes(ivBytes);
cipherAlg.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(ivBytes));
byte[] cipher = cipherAlg.doFinal(plainText);
byte[] cipherText = new byte[ivBytes.length + cipher.length];
System.arraycopy(ivBytes, 0, cipherText, 0, ivBytes.length);
System.arraycopy(cipher, 0, cipherText, ivBytes.length, cipher.length);
return cipherText;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜