2

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!

2
  • You have used little visited tags, Rotem. I'll add encryption... Feb 23, 2012 at 22:09
  • It would be nice if you followed up on your questions, Rotem. Feb 27, 2012 at 2:13

1 Answer 1

4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.