在AES / CBC / PKCS5Padding中获取'BadPaddingException:pad block corrupted'

时间:2010-07-05 04:16:18

标签: java encryption encryption-symmetric

我的常数

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

加密

   Cipher aesCipher = Cipher.getInstance(AES_ALGORITHM_MODE_PADDING, PROVIDER);
   SecretKeySpec aeskeySpec = new SecretKeySpec(rawAesKey, AES);
   aesCipher.init(Cipher.ENCRYPT_MODE, aeskeySpec);
   byte[] encryptedData = aesCipher.doFinal(data);
   this.iv = Base64.encodeBase64(aesCipher.getIV()); //get hold of the random IV

   return encryptedData;

在另一个班级我做解密

      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);

现在当我运行这个时,我在doFinal解密时遇到BadPaddingException,我做错了什么?如果我删除CBC / PKCS5Padding和IV的东西,只使用AES,它的工作原理!

1 个答案:

答案 0 :(得分:0)

您可以尝试没有填充的CTR模式:

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;