此异常通常是因为加密时使用了不同的填充方式导致的,需要在加密和解密时采用相同的填充方式。示例如下:
加密代码:
public static byte[] encrypt(byte[] keyBytes, byte[] ivBytes, byte[] plainText) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher.doFinal(plainText);
}
解密代码:
public static byte[] decrypt(byte[] keyBytes, byte[] ivBytes, byte[] cipherText) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher.doFinal(cipherText);
}
注意到加密和解密时都使用了PKCS5Padding填充方式,保证了一致性。