invalid AES key length error

silverkid picture silverkid · Nov 19, 2009 · Viewed 81.5k times · Source

this code give invalid AES key length error. how can i correct it ? ( i want 128 bit key AES encryption )

package org.temp2.cod1;
import java.security.*;

import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;

public class Code1 {

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    String s = "9882623867";
    byte[] plaintext = s.getBytes("UTF-16");
    String s2 = "supernova";
    byte[] key = s2.getBytes("UTF-16");
    Cipher c = Cipher.getInstance("AES");
    SecretKeySpec k =  new SecretKeySpec(key, "AES");
    c.init(Cipher.ENCRYPT_MODE, k);
    byte[] encryptedData = c.doFinal(plaintext);
    System.out.println(encryptedData);
}
}

any help appreciated

Answer

erickson picture erickson · Nov 19, 2009

Use a SecretKeyFactory to derive key bytes from a password.You can see a detailed example here. Note that you'll need to specify a key length of 128 bits key instead of 256 bits as shown in that example.

The next problem that you will run into is that you have not specified a padding scheme. Unless your messages are a multiple of 16 bytes (the AES block size), that will raise an error. Use PKCS5Padding as shown in the example.

Use of CBC mode on the cipher will require a new initialization vector to be chosen for each message. This unique IV must be sent along with the encrypted message to the recipient.

Trying to perform cryptography without a thorough understanding of the concepts raised here (and a lot more) is likely to result in an insecure system.