如何在Java中创建安全的随机AES密钥? [英] How to create a secure random AES key in Java?

查看:778
本文介绍了如何在Java中创建安全的随机AES密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在其他帖子中,我发现了这一点,但是使用一个 SecretKeyFactory 可能是一个更好的主意:

 <$ c $ keyGenerator keyGen = KeyGenerator.getInstance(AES); 
SecureRandom random = new SecureRandom(); //加密安全随机
keyGen.init(random);
SecretKey secretKey = keyGen.generateKey();

如果答案包含解释为什么它是生成随机的好方法键。谢谢!

解决方案

我会用你建议的代码,但稍微简化一下:


$ b KeyGenerator keyGen = KeyGenerator.getInstance(AES); $ b

  keyGen.init(256); //例如
SecretKey secretKey = keyGen.generateKey();

让提供商选择如何计划获取随机性 - 不要定义可能不是



此代码示例假定( as Maarten指出以下),您已经配置了您的 java.security 文件,以将您首选的提供程序包含在列表的顶部。如果要手动指定提供程序,只需调用 KeyGenerator.getInstance(AES,providerName);



对于真正安全的密钥,您需要使用硬件安全模块(HSM)生成和保护密钥。 HSM制造商通常将提供一个JCE提供商,使用上述代码为您完成所有的关键代码。


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!

解决方案

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.

这篇关于如何在Java中创建安全的随机AES密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆