1

For generating AES key of 256 bits, i wrote following code:

KeyGenerator keyGen;

try {
  keyGen = KeyGenerator.getInstance("AES");
  keyGen.init(256);
  SecretKey secretKey = keyGen.generateKey();
  return secretKey;    
}
catch (Exception e) {
  e.printStackTrace();
  return null;
}

My encryption method is:

  private byte[] aes256Encode(SecretKey key, IvParameterSpec iv, String message) throws InvalidKeyException,
      InvalidAlgorithmParameterException,
      NoSuchAlgorithmException, NoSuchPaddingException,
      IllegalBlockSizeException, BadPaddingException 
  {
    Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] encrypted = cipher.doFinal(message.getBytes());
    return encrypted;
  }

and IV generation method is:

  private IvParameterSpec generateAESIV() {
    // build the initialization vector (randomly).
    SecureRandom random = new SecureRandom();
    byte iv[] = new byte[16];//generate random 16 byte long
    random.nextBytes(iv);
    IvParameterSpec ivspec = new IvParameterSpec(iv);
    return ivspec;
  }

But while encryption, it is throwing following error:

Exception in thread "main" java.security.InvalidKeyException: Illegal key size
    at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1039)
    at javax.crypto.Cipher.implInit(Cipher.java:805)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
    at javax.crypto.Cipher.init(Cipher.java:1396)
    at javax.crypto.Cipher.init(Cipher.java:1327)

Can anyone point out the mistake i am making here?

Darshil Babel
  • 145
  • 1
  • 1
  • 10

2 Answers2

1

Did you update the JCE jars?.

http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java gets shipped with a default 128bit. Take a look and let me know

Aravind R
  • 716
  • 1
  • 10
  • 36
1

Change this line

keyGen.init(256);

To

keyGen.init(128);

By default, Java supports only 128-bit encryption.

Edit: If you need to encrypt content with keys larger than 128 bit, you have to use Java Cryptography Extension (JCE).

Marcelo Leite
  • 59
  • 3
  • 7