Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 316
Ronnie Avatar asked Mar 01 '13 12:03

Ronnie


2 Answers

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.

like image 82
hardartcore Avatar answered Oct 18 '22 03:10

hardartcore


To encrypt a fixed length of only 16 bytes of data, using a method that requires no initialization vector, Change AES to AES/ECB/NoPadding.

like image 32
WPrecht Avatar answered Oct 18 '22 04:10

WPrecht