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

  • 相关阅读:
    Angular入门到精通系列教程(12)- 路由(Routing)
    Angular入门到精通系列教程(11)- 模块(NgModule),延迟加载模块
    error: file '/boot/grub/i386-pc/normal.mod' not found解决方案
    mysql常用查询
    mysql数据库表中随机生成时间
    成本分析报表
    弹窗维护字段POPUP_GET_VALUES
    返回上一个屏幕
    PM停机时间问题处理
    IP41
  • 原文地址:https://www.cnblogs.com/feiyuhuo/p/8903990.html
Copyright © 2011-2022 走看看