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

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

问题描述

在 Java 中使用标准 JDK 生成安全的随机 AES 密钥的推荐方法是什么?

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

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

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.

此代码示例假定(正如 Maarten 在下面指出的)您已经配置了 java.security 文件以在列表顶部包含您的首选提供商.如果你想手动指定提供者,只需调用 KeyGenerator.getInstance("AES", "providerName");.

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");.

要获得真正安全的密钥,您需要使用硬件安全模块 (HSM)生成和保护密钥.HSM 制造商通常会提供 JCE 提供商,该提供商将使用上述代码为您生成所有密钥.

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天全站免登陆