問題描述
這段代碼安全嗎?
SecureRandom randomizer = new SecureRandom(String.valueOf(new Date().getTime()).getBytes());
這是實例化安全隨機種子的正確方法嗎?
Is this the right way to instance the seed of secure random?
推薦答案
不,你應該避免使用 SecureRandom(byte[])
構造函數.它既不安全也不便攜.
No, you should avoid the SecureRandom(byte[])
constructor. It is both unsafe and non-portable.
它是不可移植的,因為它在 Windows 和其他操作系統上的行為不同.
It is non-portable because it behaves differently on Windows vs. other operating systems.
在大多數操作系統上,默認算法是NativePRNG",它從操作系統獲取隨機數據(通常是 "/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 上,默認算法是SHA1PRNG",它將您的種子與計數器結合起來并計算結果的哈希值.
On Windows, the default algorithm is "SHA1PRNG", which combines your seed with a counter and computes a hash of the result.
在您的示例中這是個壞消息,因為輸入(當前 UTC 時間,以毫秒為單位)的可能值范圍相對較小.例如,如果攻擊者知道 RNG 是在過去 48 小時內播種的,他們可以將種子縮小到小于 228 個可能的值,即您只有 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 上使用了默認的 SecureRandom()
構造函數,它將調用本機 CryptoGenRandom
函數來獲取 128 位種子.因此,通過指定您自己的種子,您已經削弱了安全性.
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.
如果您真的想覆蓋默認種子(例如用于單元測試),您還應該指定算法.例如
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/
這篇關于Java中的SecureRandom安全種子的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!