AES Encryption Java Invalid Key length

Posted by wuntee on Stack Overflow See other posts from Stack Overflow or by wuntee
Published on 2010-04-02T19:50:26Z Indexed on 2010/04/02 19:53 UTC
Read the original article Hit count: 449

Filed under:
|
|

I am trying to create an AES encryption method, but for some reason I keep getting a 'java.security.InvalidKeyException: Key length not 128/192/256 bits'.

Here is the code:

public static SecretKey getSecretKey(char[] password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException{
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    // NOTE: last argument is the key length, and it is 256
    KeySpec spec = new PBEKeySpec(password, salt, 1024, 256);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    return(secret);
}


public static byte[] encrypt(char[] password, byte[] salt, String text) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
    SecretKey secret = getSecretKey(password, salt);

    Cipher cipher = Cipher.getInstance("AES");

    // NOTE: This is where the Exception is being thrown
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    byte[] ciphertext = cipher.doFinal(text.getBytes("UTF-8"));
    return(ciphertext);
}

Can anyone see what I am doing wrong? I am thinking it may have something to do with the SecretKeyFactory algorithm, but that is the only one I can find that is supported on the end system I am developing against. Any help would be appreciated. Thanks.

© Stack Overflow or respective owner

Related posts about java

Related posts about encryption