問題描述
這段代碼安全嗎?
SecureRandom randomizer = new SecureRandom(String.valueOf(new Date().getTime()).getBytes());
這是實(shí)例化安全隨機(jī)種子的正確方法嗎?
Is this the right way to instance the seed of secure random?
推薦答案
不,你應(yīng)該避免使用 SecureRandom(byte[])
構(gòu)造函數(shù).它既不安全也不便攜.
No, you should avoid the SecureRandom(byte[])
constructor. It is both unsafe and non-portable.
它是不可移植的,因?yàn)樗?Windows 和其他操作系統(tǒng)上的行為不同.
It is non-portable because it behaves differently on Windows vs. other operating systems.
在大多數(shù)操作系統(tǒng)上,默認(rèn)算法是NativePRNG",它從操作系統(tǒng)獲取隨機(jī)數(shù)據(jù)(通常是 "/dev/random"
)并忽略您提供的種子.
On most OSes, the default algorithm is "NativePRNG", which obtains random data from the OS (usually "/dev/random"
) and ignores the seed you provide.
在 Windows 上,默認(rèn)算法是SHA1PRNG",它將您的種子與計(jì)數(shù)器結(jié)合起來并計(jì)算結(jié)果的哈希值.
On Windows, the default algorithm is "SHA1PRNG", which combines your seed with a counter and computes a hash of the result.
在您的示例中這是個(gè)壞消息,因?yàn)檩斎?當(dāng)前 UTC 時(shí)間,以毫秒為單位)的可能值范圍相對較小.例如,如果攻擊者知道 RNG 是在過去 48 小時(shí)內(nèi)播種的,他們可以將種子縮小到小于 228 個(gè)可能的值,即您只有 27 位的熵.
This is bad news in your example, because the input (the current UTC time in milliseconds) has a relatively small range of possible values. For example if an attacker knows that the RNG was seeded in the last 48 hours, they can narrow the seed down to less than 228 possible values, i.e. you have only 27 bits of entropy.
另一方面,如果您在 Windows 上使用了默認(rèn)的 SecureRandom()
構(gòu)造函數(shù),它將調(diào)用本機(jī) CryptoGenRandom
函數(shù)來獲取 128 位種子.因此,通過指定您自己的種子,您已經(jīng)削弱了安全性.
If on the other hand you had used the default SecureRandom()
constructor on Windows, it would have called the native CryptoGenRandom
function to get a 128-bit seed. So by specifying your own seed you have weakened the security.
如果您真的想覆蓋默認(rèn)種子(例如用于單元測試),您還應(yīng)該指定算法.例如
If you really want to override the default seed (e.g. for unit testing) you should also specify the algorithm. E.g.
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed("abcdefghijklmnop".getBytes("us-ascii"));
另請參閱如何使用 Java SecureRandom 解決性能問題?
和這篇博文:http://www.cigital.com/justice-league-blog/2009/08/14/proper-use-of-javas-securerandom/
這篇關(guān)于Java中的SecureRandom安全種子的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!