0

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.

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.