0
votes

I am tying to use the AES 256 algorithm in CBC mode. The algorithm works fine (both encryption and decryption) in memory, but if I save the encrypted string into a file, the decryption algorithm fails with the following exception:

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher

My Decryption Logic

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, key, iv);
    byte[] raw = Base64.decodeBase64(encryptedString);
    byte[] stringBytes = cipher.doFinal(raw);
    String decryptedString = new String(stringBytes, "UTF8");
    return decryptedString;

Thoughts?

1
This is probably some encoding issue. Please include the complete necessary code to reproduce the issue. - Artjom B.
Could you supply sample ciphertext too? - Maarten Bodewes

1 Answers

1
votes

If your code works in-memory, then you can test the following chain:

  • get encrypted bytes array
  • write it into the file
  • read it from the file
  • compare original encrypted bytes array vs read from the file

Unit-testing forever!