随机数生成

一个小小的随机数生成

/// <summary> /// lou 2019-9-25 15:14:02 生成随机字符串 /// </summary> /// <param name="length">返回值的长度</param> /// <param name="type">返回值类型,1:纯数字;2:小写字母;3:大写字母;4:大小写字母混合;5:小写字母和数字混合;6:大写字母和数字混合;7:大小写字母和数字混合</param> /// <returns></returns> public static string GetCode(int length, int type) { string str = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ"; string retStr = ""; Random rnd = new Random(GetRandomSeed()); for (int i = 0; i < length; i++) { switch (type) { case 1: retStr += rnd.Next(10).ToString(); break; case 2: retStr += str.Substring(10 + rnd.Next(26), 1); break; case 3: retStr += str.Substring(36 + rnd.Next(26), 1); break; case 4: retStr += str.Substring(10 + rnd.Next(52), 1); break; case 5: retStr += str.Substring(0 + rnd.Next(36), 1); break; case 6: retStr += str.Substring(0 + rnd.Next(36), 1).ToUpper(); break; case 7: retStr += str.Substring(0 + rnd.Next(61), 1); break; } } if (retStr == "") { retStr = GetCode(length, type); } return retStr; } /// <summary> /// 描 述:创建加密随机数生成器 生成强随机种子 /// </summary> /// <returns></returns> private static int GetRandomSeed() { byte[] bytes = new byte[4]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); }

 

posted @ 2019-09-30 17:52  聖潔  阅读(381)  评论(0编辑  收藏  举报