'BadPaddingException: pad block corrupted' while decrypting using AES/ECB

Ronnie picture Ronnie · Mar 1, 2013 · Viewed 23.5k times · Source

In Android/java app,

byte[] data = ":ʺ$jhk¨ë‹òºÃ"; // fetched from php server..
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, mKeyspec);
return new String(cipher.doFinal(data));

The above code always throws BadPaddingException: pad block corrupted for following 16 byte encypted data

data = ":ʺ$jhk¨ë‹òºÃ" (the data is 16 chars)

The key is 16 bytes long.

Why does it throw this exception when the data is already the size of a block.? and no padding is needed.

Note: The encrypted data is fetched from a php server.

Edit:

After changing to
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
from
Cipher cipher = Cipher.getInstance("AES");

the decrypt method succeeds, but gives this output enter image description here

Answer

hardartcore picture hardartcore · Mar 1, 2013

In most cases which I've been dealing with BadPaddingException was when I was trying to decrypt something which was encrypted on server side with different padding or in some cases it wasn't even decrypted. So first of all I suggest you to look at the way and be sure that the server is returning your string not only Base64 encoded, but encrypted with AES too. Another thing to be careful is if the encryption on server side is using some kind of padding like : AES/CBC/NoPadding , AES/CBC/PKCS5Padding or AES/CBC/PKCS7Padding. In that cases you have to use the same padding in Android so you can decrypt the String.