在.NET Framework環境下生成真隨機數

這裏僅討論.NET Framework環境下的情況,在.NET Core中有變化。

真隨機數是相對於僞隨機數生成類 Random 的。

電腦產生的隨機數都是算法生成的,簡單的Random類默認使用系統時間刻度作用種子生成隨機數,因此如果在併發情況下兩個實例產生的隨機數有可能相同,也就是說有可能被預測(隨機數序列可被預測會導致很嚴重的漏洞,例如曾經有撲克牌遊戲網站由於使用了可以被預測的隨機數發生器來實現隨機發牌而導致的安全漏洞)。

所以可以使用RNGCryptoServiceProvider的實現類RandomNumberGenerator來生成隨機數,它不僅僅使用單一的系統時間元素來生成隨機數,還包含了Process ID、Thread ID以及大量系統信息。

 1 public static int Next(this RandomNumberGenerator generator, int min, int max)
 2         {
 3             // match Next of Random
 4             // where max is exclusive
 5             max = max - 1;
 6 
 7             var bytes = new byte[sizeof(int)]; // 4 bytes
 8             generator.GetNonZeroBytes(bytes);
 9             var val = BitConverter.ToInt32(bytes, 0);
10             // constrain our values to between our min and max
11             // https://stackoverflow.com/a/3057867/86411
12             var result = ((val - min) % (max - min + 1) + (max - min + 1)) % (max - min + 1) + min;
13             return result;
14         }

 

 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章