I asked this question a while ago about IVs in AES, and I got a very nice and helpful answer (thanks!) so I was thinking maybe you guys could help me out again, this time with the actual key generation.
TL;DR - See bottom
Currently, I'm encrypting like this:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
SecureRandom randomSecure = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[cipher.getBlockSize()];
randomSecure.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParams);
rawCryptotext = cipher.doFinal(textToEncrypt.getBytes());
So you can see, I am using the SecureRandom
class to generate the random IV.
However:
Notice the key
variable in the 6th line of code:
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
That variable comes from my getKey()
method, which is as follows:
public static String getKey()
{
String possibleKey = "init";
String validKey = null;
while (possibleKey.length() != 16)
{
System.out.printf("\nPlease enter a 128-bit key: ");
possibleKey = input.nextLine();
}
if (possibleKey.length() == 16)
{
validKey = possibleKey;
}
else
{
System.out.println("Something has gone very wrong...");
}
return validKey;
}
You'll notice that I get the key from the user, and pass it in plain text to SecretKeySpec
.