using System.Security.Cryptography; namespace Zhaizj.Framework.Utils { /// /// 随机数实用类 /// public static class RandomHelper { /// /// 获取随机字节序列 /// /// 字节序列的长度 /// 字节序列 public static byte[] GetRandomBytes(int length) { if(length <= 0) { return new byte[0]; } RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] ret = new byte[length]; rng.GetNonZeroBytes(ret); return ret; } /// /// 缺省的字符串取值范围 /// public const string DEFAULT_CHARLIST = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; /// /// 可读的字符串取值范围,数字与字母 /// public const string READ_CHARLIST = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; /// /// 获取随机字符串 /// /// 字符串长度 /// 字符串取值范围(如果为Null或为空,则返回空字符串) /// 随机字符串 public static string GetRandomString(int length, string charList) { if(length <= 0 || Checker.CheckEmptyString("charList", charList, false)) { return string.Empty; } int num = charList.Length; char[] ret = new char[length]; byte[] rnd = GetRandomBytes(length); for(int i = 0; i < rnd.Length; i++) { ret[i] = charList[rnd[i] % num]; } return new string(ret); } /// /// 获取随机字符串 /// /// 字符串长度 /// 随机字符串 /// /// 缺省使用ASCII从33到126共94个字符作为取值范围 /// public static string GetRandomString(int length) { return GetRandomString(length, DEFAULT_CHARLIST); } } }