2

I'm trying to create an application for Android that uses encryption to save user information and I cannot figure out what I'm doing wrong. I'm trying to create an instance of an AES cipher but the application keeps on throwing "InvalidKeyExceptions." Consider the following code:

public static final byte[] IV = new byte[]
{ 0x04, 0x08, 0x15, 0x16, 0x23, 0x42, 0x00, 0x00, 0x00, 0x00,0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
protected final IvParameterSpec params = new IvParameterSpec(IV);
protected Cipher myCipher;

public AESEncryptor(String passwd, InputStream source, String destinationFile)
{
    try
    {           
        myCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        Log.d("System.out.println", "Block Size: "+myCipher.getBlockSize());
        myCipher.init(Cipher.ENCRYPT_MODE, AESEncryptor.generateSecretKeyFromPassword(passwd),params);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

I get this exception:

java.security.InvalidKeyException: initialisation vector must be the same length as block size..

The myCipher.init(...) line triggers this exception.

I understand what it's saying but according to myCipher.getBlockSize() the IV byte array should hold 16 bytes, and it does, but it doesn't work. I have also tried byte arrays of length 0-128, and nothing in that range works either.

Oh also, if I take this code, unaltered, and add it to a regular Java application, I get no errors. Compiling for Android seems to be causing this error.

Please help. Thanks, Ryan

2
  • is that the exact text of the exception? I can't find it in the openjdk, though it is possible they changed the text. Commented Feb 15, 2010 at 12:54
  • Yes, that is the exact text. The rest of the exception is just a stack trace. They might have changed the text because "initialisation" is spelled wrong... it should be "initialization." Commented Feb 15, 2010 at 13:07

1 Answer 1

1

Have you tried specifying explicitly the block size in your mode parameter?

Ex:

Cipher.getInstance("AES/CBC16/PKCS5Padding");

I noticed here that if you don't specify the block size then it is provider dependent.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for responding. Though this is a good idea, when I tried it I got the following exception: "java.security.NoSuchAlgorithmException: can't support mode CBC16". Ryan
Try CBC128 since AES is a 128bit block cipher. Here's a good reference page: java.sun.com/j2se/1.4.2/docs/guide/security/jce/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.