問題描述
我們的團隊正在使用 SecureRandom 生成密鑰對列表(SecureRandom 被傳遞給 KeyPairGenerator).我們無法就使用以下兩個選項中的哪一個達成一致:
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:
每次我們需要生成密鑰對時都創建一個新實例
Create a new instance every time we need to generate a key pair
初始化一個靜態實例并將其用于所有密鑰對
Initialize a static instance and use it for all key pairs
哪種方法通常更好,為什么?
添加:我的直覺是第二種選擇更安全.但我唯一的論點是基于偽隨機性源自當前時間戳的假設的理論攻擊:有人可能會看到密鑰對的創建時間,猜測周圍時間間隔內的時間戳,計算可能的偽隨機序列,并獲得關鍵材料.
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.
補充:我關于基于時間戳的確定性的假設是錯誤的.這就是 Random 和 SecureRandom 之間的區別.所以,看起來答案是:就安全性而言,這并不重要.
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
類必須產生非- 每次調用的確定性輸出.
Unlike the java.util.Random
class, the java.security.SecureRandom
class must produce non-deterministic output on each call.
這意味著,在 java.util.Random
的情況下,如果您每次需要一個新的隨機數時都使用相同的種子重新創建一個實例,那么您基本上會得到 same 每次結果.但是,SecureRandom
保證不會這樣做 - 因此,每次創建單個實例或創建一個新實例 not 不會影響它生成的隨機字節的隨機性.
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.
那么,從正常的良好編碼實踐的角度來看,為什么要創建太多實例呢?
So, from just normal good coding practices view point, why create too many instances when one will do?
這篇關于SecureRandom:初始化一次還是每次都需要?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!