Question

I am trying to decrypt an encrypted data obtained from a web service using AES128 cryptography.

following is the code i am using to achieve the same.

But i always end up with the following exception: javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

public static String decrypt(String strToDecrypt)
    {

        try
        {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            final SecretKeySpec secretKey = new SecretKeySpec(AppConstants.AESEncryptionKey.getBytes("UTF8"), "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey,new IvParameterSpec(new byte[16])); //new IvParameterSpec(new byte[16])
            byte base64Data[] = Base64.encode(strToDecrypt.getBytes(), Base64.DEFAULT);
            @SuppressWarnings("unused")
            String s = base64Data.toString();
            byte decBytes[] = cipher.doFinal(base64Data);
            String decStr = new String(decBytes);
            return decStr;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

Please Pour in your valuable inputs as i am badly stuck over here.

Was it helpful?

Solution 2

You are encoding the base 64 encoded ciphertext instead of decoding it. Depending on your Base64 you need to call a function that decodes from a String or CharSequence to an array of bytes, and then decrypt that. Please test if the result is a multiple of the block size, 16 bytes for AES.

OTHER TIPS

You have to call Base64.decodeBase64(s). Then call Cipher.doFinal()

Cipher.doFinal(Base64.decodeBase64(s));

Important note

In my case this issue came because of encryption not done properly, when i try to encrypt data that time my code through error that's why in middle encryption is terminated, so once you check your encryption is working properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top