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?