public static string GeneratePassword(StringOptions options = null) { options ??= new StringOptions { RequiredLength = 10, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, RequiredUniqueChars = 4, RequireNonLetterOrDigit = true, RequireNonAlphanumeric = true }; return(GenerateRandomString(options)); }
/// <summary> /// Generates the random password. /// </summary> /// <param name="options">The options.</param> /// <returns>System.String.</returns> public static string GenerateRandomString(StringOptions options = null) { options ??= new StringOptions { RequiredLength = 10, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, RequiredUniqueChars = 4, RequireNonLetterOrDigit = true, RequireNonAlphanumeric = true }; var randomChars = new[] { "ABCDEFGHJKLMNOPQRSTUVWXYZ", // uppercase "abcdefghijkmnopqrstuvwxyz", // lowercase "0123456789", // digits "!@$?_-" // non-alphanumeric }; // Using our private randomizer var rand = RandomSeed(); var chars = new List <char>(); if (options.RequireUppercase) { chars.Insert(rand.Next(0, chars.Count), randomChars[0][rand.Next(0, randomChars[0].Length)]); } if (options.RequireLowercase) { chars.Insert(rand.Next(0, chars.Count), randomChars[1][rand.Next(0, randomChars[1].Length)]); } if (options.RequireDigit) { chars.Insert(rand.Next(0, chars.Count), randomChars[2][rand.Next(0, randomChars[2].Length)]); } if (options.RequireNonAlphanumeric) { chars.Insert(rand.Next(0, chars.Count), randomChars[3][rand.Next(0, randomChars[3].Length)]); } var rcs = randomChars[rand.Next(0, randomChars.Length)]; for (var i = chars.Count; i < options.RequiredLength || chars.Distinct().Count() < options.RequiredUniqueChars; i++) { chars.Insert(rand.Next(0, chars.Count), rcs[rand.Next(0, rcs.Length)]); } return(new string(chars.ToArray())); }