欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

随机数生成

程序员文章站 2023-11-07 15:13:16
一个小小的随机数生成 /// /// lou 2019-9-25 15:14:02 生成随机字符串 /// /// 返回值的长度 /// 返回值类型,1:纯数字;... ......
一个小小的随机数生成

/// <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); }