views:

1280

answers:

2

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

+1  A: 

You can't typically use any arbitrary key length (such as you're doing here with "supernova") for a block cipher like AES. You must use a supported key length (128, 192, 256, etc) appropriate for your algorithm of choice.

One common way to do this is to hash your passphrase (e.g., via SHA) and extract the first N bytes. This is better anyhow, as it allows you to "salt" your password with an initialization value such that no two users' "keys" are identical even if their passphrases are the same. If you're really interested in this stuff, the seminal work is Applied Cryptography (http://www.schneier.com/book-applied.html) by Bruce Schneier.

For practical implementation details, see: http://java.sun.com/developer/technicalArticles/Security/AES/AES%5Fv1.html

DarkSquid
+2  A: 

Use a SecretKeyFactory to derive key bytes from a password.You can see a detailed example here. However, I recommend using a 128-bit key instead of the AES-256 key 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.

erickson