> 文章列表 > 利用密码生成算法生成随机字符串

利用密码生成算法生成随机字符串

利用密码生成算法生成随机字符串

1)利用密码算法生成

public static string GenerateRandomPassword(){       string[] randomChars = new[] {"ABCDEFGHJKLMNOPQRSTUVWXYZ",    // uppercase "abcdefghijkmnopqrstuvwxyz",    // lowercase"0123456789",                   // digits"!@$?_-"                        // non-alphanumeric};Random rand = new Random(Environment.TickCount);List<char> chars = new List<char>();if (true)chars.Insert(rand.Next(0, chars.Count), randomChars[0][rand.Next(0, randomChars[0].Length)]);if (true)chars.Insert(rand.Next(0, chars.Count), randomChars[1][rand.Next(0, randomChars[1].Length)]);if (true)chars.Insert(rand.Next(0, chars.Count), randomChars[2][rand.Next(0, randomChars[2].Length)]);if (true)chars.Insert(rand.Next(0, chars.Count), randomChars[3][rand.Next(0, randomChars[3].Length)]);for (int i = chars.Count; i < 24; i++){string rcs = randomChars[rand.Next(0, randomChars.Length)];chars.Insert(rand.Next(0, chars.Count), rcs[rand.Next(0, rcs.Length)]);}return new string(chars.ToArray());}

2)和上面类似

public static string GetRandomString(int length, bool useNum = true, bool useLow = true, bool useUpp = true, bool useSpe = false){RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();byte[] data = new byte[length];string result = null, str = "";if (useNum == true) { str += "0123456789"; }if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }if (useSpe == true) { str += "!\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~"; }rng.GetBytes(data);for (int i = 0; i < length; i++){                result += str.Substring(data[i]%str.Length, 1);}return result;}