C#使用 RNGCryptoServiceProvider 生成強隨機字符串


為了生成更加可靠的隨機數,微軟在System.Security.Cryptography命名空間下提供一個名為system.Security.Cryptography.RNGCryptoServiceProvider的類,它采用系統當前的硬件信息、進程信息、線程信息、系統啟動時間和當前精確時間作為填充因子,通過更好的算法生成高質量的隨機數,生成強隨機字符串的方法如下所示:

 1 using System.Security.Cryptography;
 2 sealed class RNGCryptoRandomService
 3 {
 4     private static RNGCryptoServiceProvider _random = new RNGCryptoServiceProvider();
 5 
 6     public static string GetRandomString(int stringlength)
 7     {
 8         return GetRandomString(null, stringlength);
 9     }
10 
11     //獲得長度為stringLength的隨機字符串,以key為字母表
12     public static string GetRandomString(string key, int stringLength)
13     {
14         if (key == null || key.Length < 8)
15         {
16             key = "abcdefghijklmnopqrstuvwxyz1234567890";
17         }
18 
19         int length = key.Length;
20         StringBuilder randomString = new StringBuilder(length);
21         for (int i = 0; i < stringLength; ++i)
22         {
23             randomString.Append(key[SetRandomSeeds(length)]);
24         }
25 
26         return randomString.ToString();
27     }
28 
29     private static int SetRandomSeeds(int length)
30     {
31         decimal maxValue = (decimal)long.MaxValue;
32         byte[] array = new byte[8];
33         _random.GetBytes(array);
34 
35         return (int)(Math.Abs(BitConverter.ToInt64(array, 0)) / maxValue * length);
36     }
37 }                            

總結

Random算法簡單,性能較高,適用於隨機性要求不高的情況,由於RNGCryptoServiceProvider在生成期間需要查詢上面提到的幾種系統因子,所以性能稍弱於Random類,但隨機數質量高,可靠性更好。使用哪一種方式視情況而定。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM