user538565
user538565

Reputation: 513

Android AES problem

I'm tring to encrypt/decrypt my files using AES. I followed this tutorial to encrypt my data, but I modified the code a little bit, so that I could use the same key to encrypt many files.

In addition to encrypting my files, my AES key is also saved using RSA (this page , saveKey() method).

I encrypted files on my PC, and tried to decrypt them on Android. However, I always got BadPaddingException: pad block corrupted. I printed out the AES keys, and found out that with the same private key, the decrypted AES keys were different on PC and Android.

It worked fine if I decrypt the same files on PC.

Why?!

Is there anything wrong with Android's cipher?! Help needed.

Upvotes: 3

Views: 1463

Answers (2)

Ian Low
Ian Low

Reputation: 399

your RSA padding cipher could be on the wrong padding scheme

try this?

pkCipher = Cipher.getInstance("RSA/NONE/PKCS1Padding");

Upvotes: 3

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52936

The code you copied is wrong. It may or may not work depending on Android version. My guess is that it doesn't on newer ones. The part which converts from seed to raw key is flawed (see below): SecureSeed.setSeed() is not guaranteed to set the random generator state, it just adds to it. What this means is that you are not guaranteed to get the same key. To reliably get the same key based on a password, you need to use PBE (Password Based Encryption)

 private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    // this is wrong!
    sr.setSeed(seed);
    kgen.init(128, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}

Generally, first make sure you can reliably encrypt/decrypt using AES, then you might move on to using RSA. You might want to tell us what you are trying to achieve, you might be going at it the wrong way. Inventing your own cryptographic protocol is rarely a good idea.

Upvotes: 1

Related Questions