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类,但随机数质量高,可靠性更好。使用哪一种方式视情况而定。

posted @ 2018-04-21 22:02  Nullobj  阅读(5660)  评论(0编辑  收藏  举报