2
votes

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!

1
You have used little visited tags, Rotem. I'll add encryption... - Maarten Bodewes
It would be nice if you followed up on your questions, Rotem. - Maarten Bodewes

1 Answers

4
votes

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