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 }
C#使用 RNGCryptoServiceProvider 生成强随机字符串
猜你喜欢
转载自www.cnblogs.com/feiyuhuo/p/8903990.html
今日推荐
周排行