![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yXD9FdvwFNyYTO3MzLcVXeulGezF2Lc12bj91cn9Gbi52YvwVbvNmLzd2bsJmbj5ycldWYtl2Lc9CX6MHc0RHaiojIsJye.png)
真正意義上的随機數(或者随機事件)在某次産生過程中是按照實驗過程中表現的分布機率随機産生的,其結果是不可預測的,是不可見的。而計算機中的随機函數是按照一定算法模拟産生的,其結果是确定的,是可見的。我們可以這樣認為這個可預見的結果其出現的機率是100%。是以用計算機随機函數所産生的“随機數”并不随機,是僞随機數。僞随機數的作用在開發中的使用非常常見,是以.NET在System命名空間,提供了一個簡單的Random随機數生成類型。但這個類型并不能滿足所有的需求,本節開始就将陸續介紹Math.NET中有關随機數的擴充以及其他僞随機生成算法編寫的随機數生成器。
本部落格所有文章分類的總目錄:【總目錄】本部落格博文總目錄-實時更新
開源Math.NET基礎數學類庫使用總目錄:【目錄】開源Math.NET基礎數學類庫使用總目錄
前言
真正意義上的随機數(或者随機事件)在某次産生過程中是按照實驗過程中表現的分布機率随機産生的,其結果是不可預測的,是不可見的。而計算機中的随機函數是按照一定算法模拟産生的,其結果是确定的,是可見的。我們可以這樣認為這個可預見的結果其出現的機率是100%。是以用計算機随機函數所産生的“随機數”并不随機,是僞随機數。僞随機數的作用在開發中的使用非常常見,是以.NET在System命名空間,提供了一個簡單的Random随機數生成類型。但這個類型并不能滿足所有的需求,本節開始就将陸續介紹Math.NET中有關随機數的擴充以及其他僞随機生成算法編寫的随機數生成器。
今天要介紹的是Math.NET中利用C#快速的生成安全的随機數。
如果本文資源或者顯示有問題,請參考 本文原文位址:http://www.cnblogs.com/asxinyu/p/4301554.html
1.什麼是安全的随機數?
Math.NET在MathNet.Numerics.Random命名空間中的實作了一個基于System.Security.Cryptography.RandomNumberGenerator的安全随機數發生器。
實際使用中,很多人對這個不在意,那麼Random和安全的随機數有什麼差別,什麼是安全的随機數呢?
在許多類型軟體的開發過程中,都要使用随機數。例如紙牌的分發、密鑰的生成等等。随機數至少應該具備兩個條件:
1. 數字序列在統計上是随機的。
2. 不能通過已知序列來推算後面未知的序列。
隻有實際實體過程才是真正随機的。而一般來說,計算機是很确定的,它很難得到真正的随機數。是以計算機利用設計好的一套算法,再由使用者提供一個種子值,得出被稱為“僞随機數”的數字序列,這就是我們平時所使用的随機數。
這種僞随機數字足以滿足一般的應用,但它不适用于加密等領域,因為它具有弱點:
1. 僞随機數是周期性的,當它們足夠多時,會重複數字序列。
2. 如果提供相同的算法和相同的種子值,将會得出完全一樣的随機數序列。
3. 可以使用逆向工程,猜測算法與種子值,以便推算後面所有的随機數列。
對于這個随機數發生器,本人深有體會,在研究所學生期間,我的研究方向就是 流密碼,其中一個主要的課題就是 如何生成高安全性能的随機數發生器,研究了2年吧,用的是 混沌生成僞随機數,用于加密算法。.NET自帶的Random類雖然能滿足正常要求,但在一些高安全場合,是不建議使用的,因為其生成的随機數是可以預測和破解的。是以在.net中也提供了一個用于加密的RandomNumberGenerator。Math.NET就是該類的一個翻版。雖然其效率要比Random更低,但是更安全。
2..NET中使用RNGCryptoServiceProvider的例子
RNGCryptoServiceProvider的使用可以參考一個MSDN的例子:
1 using System;
2 using System.IO;
3 using System.Text;
4 using System.Security.Cryptography;
5
6 class RNGCSP
7 {
8 public static void Main()
9 {
10 for(int x = 0; x <= 30; x++)
11 Console.WriteLine(RollDice(6));
12 }
13
14 public static int RollDice(int NumSides)
15 {
16 byte[] randomNumber = new byte[1];
17
18 RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
19
20 Gen.GetBytes(randomNumber);
21
22 int rand = Convert.ToInt32(randomNumber[0]);
23
24 return rand % NumSides + 1;
25 }
26 }
3.Math.NET中安全随機數類的實作
随機數生成器算法的實作基本都類似,這裡就看一下Math.NET中安全的随機數生成器CryptoRandomSource類的實作:
1 public sealed class CryptoRandomSource : RandomSource, IDisposable
2 {
3 const double Reciprocal = 1.0/uint.MaxValue;
4 readonly RandomNumberGenerator _crypto;
5
6 /// <summary>
7 /// Construct a new random number generator with a random seed.
8 /// </summary>
9 /// <remarks>Uses <see cref="System.Security.Cryptography.RNGCryptoServiceProvider"/> and uses the value of
10 /// <see cref="Control.ThreadSafeRandomNumberGenerators"/> to set whether the instance is thread safe.</remarks>
11 public CryptoRandomSource()
12 {
13 _crypto = new RNGCryptoServiceProvider();
14 }
15
16 /// <summary>
17 /// Construct a new random number generator with random seed.
18 /// </summary>
19 /// <param name="rng">The <see cref="RandomNumberGenerator"/> to use.</param>
20 /// <remarks>Uses the value of <see cref="Control.ThreadSafeRandomNumberGenerators"/> to set whether the instance is thread safe.</remarks>
21 public CryptoRandomSource(RandomNumberGenerator rng)
22 {
23 _crypto = rng;
24 }
25
26 /// <summary>
27 /// Construct a new random number generator with random seed.
28 /// </summary>
29 /// <remarks>Uses <see cref="System.Security.Cryptography.RNGCryptoServiceProvider"/></remarks>
30 /// <param name="threadSafe">if set to <c>true</c> , the class is thread safe.</param>
31 public CryptoRandomSource(bool threadSafe) : base(threadSafe)
32 {
33 _crypto = new RNGCryptoServiceProvider();
34 }
35
36 /// <summary>
37 /// Construct a new random number generator with random seed.
38 /// </summary>
39 /// <param name="rng">The <see cref="RandomNumberGenerator"/> to use.</param>
40 /// <param name="threadSafe">if set to <c>true</c> , the class is thread safe.</param>
41 public CryptoRandomSource(RandomNumberGenerator rng, bool threadSafe) : base(threadSafe)
42 {
43 _crypto = rng;
44 }
45
46 /// <summary>
47 /// Returns a random number between 0.0 and 1.0.
48 /// </summary>
49 /// <returns>
50 /// A double-precision floating point number greater than or equal to 0.0, and less than 1.0.
51 /// </returns>
52 protected override sealed double DoSample()
53 {
54 var bytes = new byte[4];
55 _crypto.GetBytes(bytes);
56 return BitConverter.ToUInt32(bytes, 0)*Reciprocal;
57 }
58
59 public void Dispose()
60 {
61 #if !NET35
62 _crypto.Dispose();
63 #endif
64 }
65
66 /// <summary>
67 /// Fills an array with random numbers greater than or equal to 0.0 and less than 1.0.
68 /// </summary>
69 /// <remarks>Supports being called in parallel from multiple threads.</remarks>
70 public static void Doubles(double[] values)
71 {
72 var bytes = new byte[values.Length*4];
73
74 #if !NET35
75 using (var rnd = new RNGCryptoServiceProvider())
76 {
77 rnd.GetBytes(bytes);
78 }
79 #else
80 var rnd = new RNGCryptoServiceProvider();
81 rnd.GetBytes(bytes);
82 #endif
83
84 for (int i = 0; i < values.Length; i++)
85 {
86 values[i] = BitConverter.ToUInt32(bytes, i*4)*Reciprocal;
87 }
88 }
89
90 /// <summary>
91 /// Returns an array of random numbers greater than or equal to 0.0 and less than 1.0.
92 /// </summary>
93 /// <remarks>Supports being called in parallel from multiple threads.</remarks>
94 [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
95 public static double[] Doubles(int length)
96 {
97 var data = new double[length];
98 Doubles(data);
99 return data;
100 }
101
102 /// <summary>
103 /// Returns an infinite sequence of random numbers greater than or equal to 0.0 and less than 1.0.
104 /// </summary>
105 /// <remarks>Supports being called in parallel from multiple threads.</remarks>
106 public static IEnumerable<double> DoubleSequence()
107 {
108 var rnd = new RNGCryptoServiceProvider();
109 var buffer = new byte[1024*4];
110
111 while (true)
112 {
113 rnd.GetBytes(buffer);
114 for (int i = 0; i < buffer.Length; i += 4)
115 {
116 yield return BitConverter.ToUInt32(buffer, i)*Reciprocal;
117 }
118 }
119 }
120 }
4.資源
源碼下載下傳:http://www.cnblogs.com/asxinyu/p/4264638.html
如果本文資源或者顯示有問題,請參考 本文原文位址:http://www.cnblogs.com/asxinyu/p/4301519.html
.NET資料挖掘與機器學習,作者部落格:
http://www.cnblogs.com/asxinyu
E-mail:[email protected]