加密和Java,生成密钥的方法-什么大小?
我得到以下方法主体来生成加密密钥:
new BigInteger(500, new SecureRandom()).toString(64);
任何人都可以解释生成的密钥的大小是多少吗?
I got the following method body to generate a key for encryption:
new BigInteger(500, new SecureRandom()).toString(64);
Could anyone explain what is the size of generated key?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在您的情况下,它是一个长度为 500 位的安全随机数。查看 BigInteger(int numBits, Random rnd) 构造函数的 javadoc。
It's a secure random number with a length of 500 bit in your case. Have a look at the javadoc of the BigInteger(int numBits, Random rnd) constructor.
您的代码行创建了一个 500 位整数,并且显然尝试将其转换为 Base64 格式的字符串 - 这就是
toString()
调用。但这是行不通的,因为 BigInteger.toString() 仅适用于基数 36,否则默认为十进制。如果您需要 Base64 表示,则必须使用第三方类,因为标准 API 中没有 Base64 编码器。Your line of code creates a 500 bit integer and apparently tries to convert it to a String in Base64 - that's the
toString()
call. But that won't work, because BigInteger.toString() only works up to base 36 and defaults to decimal otherwise. If you need a Base64 representation, you have to use a third-party class, as there is AFAIK no Base64 encoder in the standard API.通常您会希望您的加密密钥是 2 的幂。那么也许您的意思是 512 位?
Normally you would want your encryption key to be a power of 2. So perhaps you mean 512 bits?
首先,正如其他人所建议的,您将得到 IllegalArgumentException,因为 BigInteger 不支持基数 64。
即使您使用有效的基数,生成的字符数也会有所不同,因为 BigInteger 会去除前导 0,并且您还可能在字符串中得到减号。
要获得随机密钥,只需直接使用随机字节即可。假设您想要 128 位(16 字节)AES 密钥,只需这样做,
First, as other suggested, you will get IllegalArgumentException because BigInteger doesn't support radix 64.
Even if you use a valid radix, the number of characters generated varies because BigInteger strips leading 0s and you might also get minus sign in the string.
To get random keys, just use random bytes directly. Say you want 128-bit (16 bytes) AES key, just do this,