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

|
| By Webner

We were getting following exception when trying to decrypt data using Cipher:

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

Actually we were using three layers of encryption with three different secret keys. Everything was right when we were encrypting our data. Keys we were using were in the form of ByteBuffer array. After encrypting we were saving the output in a database table in the form of character string . When we trying to decrypt the value later on, it was throwing above exception.

This is the sample code for decryption:

public ByteBuffer functionName(ByteBuffer new3rdLevelKey, ByteBuffer encryptingKey)
{
String decryptedKey = null;
try
{
String key =new String(new3rdLevelKey.array());
decryptedKey = Utils.aesDecode(key.getBytes(), new String(encryptingKey.array(), "UTF-8"));
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}

The problem we found was that we were not using proper encoding to convert encoded string back to bytes. The line String key = new String(new3rdLevelKey.array()) was causing the issue because we were using UTF-8 encoding (at encryption time) but at decryption time we were not passing any encoding type so it was using default JVM encoding.

In this case we changed the line

decryptedKey = Utils.aesDecode(key.getBytes(), new String(encryptingKey.array(), "UTF-8"));

to

decryptedKey = Utils.aesDecode(new3rdLevelKey.array(), new String(encryptingKey.array(), "UTF-8"))

And issue was fixed.

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Leave a Reply

Your email address will not be published. Required fields are marked *