問題描述
我們的團(tuán)隊(duì)正在使用 SecureRandom 生成密鑰對(duì)列表(SecureRandom 被傳遞給 KeyPairGenerator).我們無(wú)法就使用以下兩個(gè)選項(xiàng)中的哪一個(gè)達(dá)成一致:
Our team is using a SecureRandom to generate a list of key pairs (the SecureRandom is passed to a KeyPairGenerator). We cannot agree on which of the following two options to use:
每次我們需要生成密鑰對(duì)時(shí)都創(chuàng)建一個(gè)新實(shí)例
Create a new instance every time we need to generate a key pair
初始化一個(gè)靜態(tài)實(shí)例并將其用于所有密鑰對(duì)
Initialize a static instance and use it for all key pairs
哪種方法通常更好,為什么?
添加:我的直覺是第二種選擇更安全.但我唯一的論點(diǎn)是基于偽隨機(jī)性源自當(dāng)前時(shí)間戳的假設(shè)的理論攻擊:有人可能會(huì)看到密鑰對(duì)的創(chuàng)建時(shí)間,猜測(cè)周圍時(shí)間間隔內(nèi)的時(shí)間戳,計(jì)算可能的偽隨機(jī)序列,并獲得關(guān)鍵材料.
ADDED: My gut feeling is that the second option is more secure. But my only argument is a theoretical attack based on the assumption that the pseudorandomness is derived from the current timestamp: someone may see the creation time of the key pair, guess timestamps in the surrounding time interval, compute the possible pseudorandom sequences, and obtain the key material.
補(bǔ)充:我關(guān)于基于時(shí)間戳的確定性的假設(shè)是錯(cuò)誤的.這就是 Random 和 SecureRandom 之間的區(qū)別.所以,看起來(lái)答案是:就安全性而言,這并不重要.
ADDED: My assumption about determinism based on a timestamp was wrong. That's the difference between Random and SecureRandom. So, it looks like the answer is: in terms of security it doesn't really matter.
推薦答案
與 java.util.Random
類不同,java.security.SecureRandom
類必須產(chǎn)生非- 每次調(diào)用的確定性輸出.
Unlike the java.util.Random
class, the java.security.SecureRandom
class must produce non-deterministic output on each call.
這意味著,在 java.util.Random
的情況下,如果您每次需要一個(gè)新的隨機(jī)數(shù)時(shí)都使用相同的種子重新創(chuàng)建一個(gè)實(shí)例,那么您基本上會(huì)得到 same 每次結(jié)果.但是,SecureRandom
保證不會(huì)這樣做 - 因此,每次創(chuàng)建單個(gè)實(shí)例或創(chuàng)建一個(gè)新實(shí)例 not 不會(huì)影響它生成的隨機(jī)字節(jié)的隨機(jī)性.
What that means is, in case of java.util.Random
, if you were to recreate an instance with the same seed each time you needed a new random number, you would essentially get the same result every time. However, SecureRandom
is guaranteed to NOT do that - so, creating a single instance or creating a new one each time does not affect the randomness of the random bytes it generates.
那么,從正常的良好編碼實(shí)踐的角度來(lái)看,為什么要?jiǎng)?chuàng)建太多實(shí)例呢?
So, from just normal good coding practices view point, why create too many instances when one will do?
這篇關(guān)于SecureRandom:初始化一次還是每次都需要?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!