java AES 密钥是随机的吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10252449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is AES key random?
提问by user249654
AES key may be generate by this code
AES 密钥可以由此代码生成
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
but
但
If I have a "very reliable" method of generating random numbers can I use it in such a way
如果我有一种“非常可靠”的生成随机数的方法,我可以这样使用它吗
SecureRandom rnd = new SecureRandom();
byte[] key = new byte[16];
rnd.nextBytes(key);
is key obtained by this method reliable ?
通过这种方法获得的密钥可靠吗?
or it ONLY must generated by some SPECIAL algorithm
或者它只能由某些特殊算法生成
回答by maybeWeCouldStealAVan
The AES key canbe any 128 bits. It shouldbe be practically unguessable, whatever the method of creating it.
AES 密钥可以是任何 128 位。无论创建它的方法如何,它都应该是几乎不可猜测的。
For Example:
例如:
SecureRandom sr = new SecureRandom()
key = new byte[16];
iv = new byte[16];
sr.nextBytes(key);
sr.nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(IV));
SecretKeySpec
, by the way, is just a thin wrapper around a byte[] --- it does not transform the key in any way. No "special algorithm".
SecretKeySpec
顺便说一下,它只是一个围绕 byte[] 的薄包装——它不会以任何方式转换密钥。没有“特殊算法”。
回答by Jason Kleban
To add to the other answers ... I believe that the reason that the basic Random functions aren't secure are two reasons:
添加到其他答案......我相信基本 Random 函数不安全的原因有两个:
- Slight statistical biases that are acceptable for non-security related situations, but narrow the distributions unacceptably for security applications.
- They are seeded by the system DATETIME. Even knowing WHEN you generated your key - to a poor accuracy of +/- 6 months - would significantly reduce the brute force search space.
- 轻微的统计偏差对于与安全无关的情况是可以接受的,但对于安全应用程序来说,分布范围会缩小到不可接受的范围。
- 它们由系统 DATETIME 播种。即使知道您何时生成密钥 - +/- 6 个月的准确性很差 - 也会显着减少蛮力搜索空间。
回答by alain.janinm
You can add a random algorithm using SecureRandom:
您可以使用SecureRandom添加随机算法:
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom(); // cryptograph. secure random
keyGen.init(random);
SecretKey secretKey = keyGen.generateKey();
回答by Tom
It sounds like you're trying to generate an AES key based on a password.
听起来您正在尝试根据密码生成 AES 密钥。
If this is the case, you can use javax.crypto.SecretKeyFactory's generateSecret
method, passing in a javax.crypto.spec.PBEKeySpec as the parameter. The PBEKeySpec allows to to specify the password as an argument to its constructor.
如果是这种情况,您可以使用 javax.crypto.SecretKeyFactory 的generateSecret
方法,传入 javax.crypto.spec.PBEKeySpec 作为参数。PBEKeySpec 允许将密码指定为其构造函数的参数。