Shan
Shan

Reputation: 2832

Android AES Encryption error during decrypting

I know nothing about AES encryption in Android/Java

I got this code from here http://www.androidsnippets.com/encryptdecrypt-strings

and I am getting the below error when it is getting decrypted whether there is some problem with my code?(I am passing the encrypted value from one activity to another)

 05-18 13:49:58.828: W/System.err(3350): javax.crypto.BadPaddingException: pad block   corrupted
 05-18 13:49:59.133: W/System.err(3350):    at org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(JCEBlockCipher.java:653)
 05-18 13:49:59.148: W/System.err(3350):    at javax.crypto.Cipher.doFinal(Cipher.java:1116)
 05-18 13:49:59.153: W/System.err(3350):    at com.spacenext.noserver2.SimpleCrypto.decrypt(SimpleCrypto.java:55)
 05-18 13:49:59.158: W/System.err(3350):    at com.spacenext.noserver2.SimpleCrypto.decrypt(SimpleCrypto.java:28)

Encryption

 05-18 15:07:32.283: I/Home(3341): 530AEA4983C93379EB512387B4E547522C1E310AD6E7752AF5B9F91C329D313315FDDA853E60C78EA618211A37BA8A47

Encryption message received at another activity

 05-18 15:07:55.382: I/Home(7871): 530AEA4983C93379EB512387B4E547522C1E310AD6E7752AF5B9F91C329D313315FDDA853E60C78EA618211A37BA8A47

Both are same but when the message is decrypted at another activity it throwns an error message..

Upvotes: 0

Views: 684

Answers (1)

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52936

This code uses a weak key derivation procedure, consider using standard password based encryption to derive your key.

The cause of your error is most probably that you are using the wrong key for decryption. Print it out in hex form and compare to your encryption key (output of getRawKey()). If you customized the code somehow, show relevant parts. How are you passing the encrypted value? Is it somehow encoded? Also check that the size is as expected in the decrypting activity.

Since encryption and decryption are done on different devices, and there is a server involved. here are a few more things to check/keep in mind:

  1. Make sure that the cipher text you send from device A is what is received on device B. There might be encoding issues involved.
  2. Don't use the default parameters for mode and padding. Those might different across your devices. Specify them explicitly like so Cipher.getInstance("AES/CBC/PKCS5Padding")
  3. Make sure you send the IV along with the cipher text. Otherwise a random one might be generated automatically, and you won't be able to decrypt.

Upvotes: 1

Related Questions