Himanshu
Himanshu

Reputation: 1086

AES Decryption: javax.crypto.BadPaddingException: pad block corrupted in Android

I am stuck with a problem with AES Decryption in my android Application. I have searched a lot but unable to get the solution.

Here are the steps, what i am doing.

Also encrypted information is not same coming from the server, what we have send in encrypted format. While the same thing is done in iPhone app, and iPhone is able to decrypt the information successfully.

I am using the following code for encryption and decryption.

public class AES256Cipher {

    public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

    public static String AES_Encode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

        byte[] textBytes = str.getBytes("UTF-8");
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
             SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
             Cipher cipher = null;
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);

        return Base64.encodeToString(cipher.doFinal(textBytes), 0);
    }

    public static String AES_Decode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

        byte[] textBytes =Base64.decode(str,0);
        //byte[] textBytes = str.getBytes("UTF-8");
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
        return new String(cipher.doFinal(textBytes), "UTF-8");
    }

Please suggest.

EDIT: I one more thing, it is working for < 16 digits information. When we put the 16 digit information, then it is throwing the Exception in decryption.

Upvotes: 0

Views: 13930

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93948

If the server encounters unknown encodings that don't map to specific characters then the key will not transfer properly and fail once in a while, resulting in an incorrect key. The ciphertext is encoded using base64 so that's probably OK, but your key may not be so lucky.

Note that any change in the key or the last blocks of the ciphertext is likely to result in a BadPaddingException.

Upvotes: 3

Related Questions