Abishek KJ
Abishek KJ

Reputation: 1

JAVA - AES Decryption - Input length must be multiple of 16 when decrypting with padded cipher

I am trying to decrypt the ResponseText variable which i get from an API. I am getting the following error.

Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be 
  multiple of 16 when decrypting with padded cipher

Below is my code snippet for decrypting the response. The Decrytpt method is throwing the error.

public static String decrypt(String encryptedText) throws Exception 
{
        Key key = generateKey();
        Cipher chiper = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        chiper.init(Cipher.DECRYPT_MODE, key, ivspec);
        byte[] encVal = chiper.doFinal(encryptedText.getBytes("UTF-8"));
        Base64.Encoder base64Encoder = Base64.getEncoder();
        String decryptedValue = base64Encoder.encodeToString(encVal);
        String decryptedString= new String("");                
        return decryptedString;
}

I have not posted the actual encrypted value here as the length of the encrypted value is too high. I am new to Java. Thanks in advance.

Upvotes: 0

Views: 797

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93978

You should probably base 64 decode the ciphertext, decrypt the binary ciphertext and then decode the resulting plaintext to UTF-8.

You haven't correctly reversed the encryption routine (encode UTF-8, encrypt, encode base64), in other words.


There is a generateKey() for the decryption; unless it returns a static value (and doesn't generate one, as the method name implies) decryption will likely fail. So either the name is wrong, or the decryption.

The IV doesn't seem to be included with the ciphertext either, which will mean that that's the next problem to deal with.

Finally, you will want to know how to handle exceptions for encryption / decryption routines.

Upvotes: 2

Related Questions