How to create a secure random AES key in Java?

前端 未结 3 1119
既然无缘
既然无缘 2020-12-02 11:50

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 SecretKeyFac

3条回答
  •  甜味超标
    2020-12-02 12:32

    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.

提交回复
热议问题