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.
After changing toCipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
fromCipher cipher = Cipher.getInstance("AES");
the decrypt method succeeds, but gives this output
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With