How to create a secure random AES key in Java?

barfuin picture barfuin · Aug 14, 2013 · Viewed 124k times · Source

What is the recommended way of generating a secure, random AES key in Java, using the standard JDK?

In other posts, I have found this, but using a SecretKeyFactory might be a better idea:

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom(); // cryptograph. secure random 
keyGen.init(random); 
SecretKey secretKey = keyGen.generateKey();

It would be great if the answer included an explanation of why it is a good way of generating the random key. Thanks!

Answer

Duncan Jones picture Duncan Jones · Aug 14, 2013

I would use your suggested code, but with a slight simplification:

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // for example
SecretKey secretKey = keyGen.generateKey();

Let the provider select how it plans to obtain randomness - don't define something that may not be as good as what the provider has already selected.

This code example assumes (as Maarten points out below) that you've configured your java.security file to include your preferred provider at the top of the list. If you want to manually specify the provider, just call KeyGenerator.getInstance("AES", "providerName");.

For a truly secure key, you need to be using a hardware security module (HSM) to generate and protect the key. HSM manufacturers will typically supply a JCE provider that will do all the key generation for you, using the code above.