AES/CBC/PKCS5Padding Java Encrypting Error - javax.crypto.BadPaddingException: Given final block not properly padded
21,619
You are not transfering either the key or the cipher text correctly, as this code does run:
private static void testCode() {
try {
String stringDec = "Hi there";
SecretKey aesKey = new SecretKeySpec(new byte[16], "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
// no encoding given, don't use getBytes() without a Charset.forName("UTF-8")
byte[] data = cipher.doFinal(stringDec.getBytes());
byte[] iv = cipher.getIV();
// doesn't do anything
AlgorithmParameters.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
byte[] decrypted = cipher.doFinal(data);
System.out.println(new String(decrypted));
} catch (GeneralSecurityException e) {
throw new IllegalStateException(e);
}
}
Author by
Admin
Updated on February 21, 2020Comments
-
Admin about 4 years
I'm trying to do encryption-decryption of a String using AES/CBC/PKCS5Padding I'm getting this Exception: javax.crypto.BadPaddingException: Given final block not properly padded
the string i'm trying to encrypt: ftp.clarapoint.com
Here is my encryption code:
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, aesKey); byte[] data = cipher.doFinal(stringDec.getBytes()); byte[] iv = cipher.getIV();
I'm transfering the decryption method the following: aesKey, data and iv
the decryption code:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); AlgorithmParameters.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv)); byte[] decrypted = cipher.doFinal(data);
Thanks!