Reputation: 746
I've been trying to get AES encryption and decryption working for some time in Java. Unfortunately I haven't had much luck. Right now I can generate a key in one method the code for which is shown
keyGen = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance();
keyGen.init(size, random);
SecretKey key = keyGen.generateKey();
AesKey = key.getEncoded();
To use the key I convert it back to a SecretKeySpec and attempt to encrypt the input bytes. My code for encryption is shown below.
SecretKeySpec keySpec = new SecretKeySpec(AesKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
return cipher.doFinal(input);
However, when I call the cipher.init line I get an InvalidKeyException.
Am I generating the key incorrectly? Am I loading the key incorrectly? Is it a combination? I'm stuck on this so any insight would be appreciated.
So I didn't realize it, but the part that was calling the generate function was passing in an invalid size. When I found that bit of the code and changed it to 256 everything works as it should.
Upvotes: 2
Views: 2127
Reputation: 746
The code that was calling the generate function was passing an invalid size. I thought that would be caught by the keyGen.generateKey() line but I was mistaken. It didn't throw the error until I actually tried to use the key. Changing the code that called the generate function so that size was 256 fixed the problem.
Upvotes: 1