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

  • 相关阅读:
    利用webpack构建vue项目
    关于写毕业设计网页代码写后感
    用canvas属性写一个五角星哦
    css3瀑布流布局
    css3学习笔记,随时帮你记起遗忘的css3
    自己做得一个用于直观观察css3 transform属性中的rotate 3D效果
    第一次讨论——关于块级元素与行内元素的区别,浮动与清除浮动,定位,兼容性问题
    软件工程第一次作业
    自我介绍
    自我介绍
  • 原文地址:https://www.cnblogs.com/feiyuhuo/p/8903990.html
Copyright © 2011-2022 走看看