3

This is my code for AES.

Under Gingerbread I get following error after encrypting the data on 2.2 then trying to decrypt on 2.3:

 Caused by: javax.crypto.BadPaddingException: pad block corrupted
        at org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(JCEBlockCipher.java:715)
        at javax.crypto.Cipher.doFinal(Cipher.java:1090)
        at com.citc.wallet.util.security.SimpleCrypto.decrypt(SimpleCrypto.java:63)
        ... 21 more

I have found some posts saying that SecureRandom is producing different results under different systems:

BouncyCastle AES error when upgrading to 1.45

How do I avoid this problem on 2.3?
Can I somehow force 2.3 to use the same SecureRandom class?
Do I need to use some portable encryption method and if so what?

Community
  • 1
  • 1
timothyjc
  • 2,188
  • 3
  • 29
  • 54

1 Answers1

4

The answer is that you shouldn't really be doing what you are doing at all. Here is the culprit:

sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();

You should never pad your key with some un-predictable random value because you will need to recreate this same exact key later on. Here are some key lines from the android docs

"Seeding SecureRandom may be insecure"

Although it is common practice to seed Random with the current time, that is dangerous with SecureRandom since that value is predictable to an attacker and not appropriate for secure use.

Anyway, I know your argument will be that you are just "padding" the key and the security of what you are doing is not a big deal.

If you are going to accept keys of 128 bits for 192 or 256 bit implementations, then you must implement a repeatable method of expanding the key to 192 or 256 bits. You can even add all 0's to the key if you wanted to, but the key really is that it must be done in some way that you can repeat it on every system.

In any case, you may also want to consider that what you are doing may be used on systems other than Android. In those cases, using a more "portable" method to expand a key should be chosen.

Community
  • 1
  • 1
Justin Breitfeller
  • 13,737
  • 4
  • 39
  • 47