You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

95 lines
3.0 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Swift.web.Library
{
public static class PasswordGenerator
{
public class PasswordOptions
{
public int RequiredLength { get; set; }
public int RequiredUniqueChars { get; set; }
public bool RequireLowercase { get; set; }
public bool RequireDigit { get; set; }
public bool RequireUppercase { get; set; }
public bool RequireNonAlphanumeric { get; set; }
}
public static string GenerateRandomPassword(PasswordOptions opts = null)
{
if (opts == null) opts = new PasswordOptions()
{
RequiredLength = 8,
RequiredUniqueChars = 4,
RequireDigit = true,
RequireLowercase = true,
RequireNonAlphanumeric = true,
RequireUppercase = true
};
string[] randomChars = new[] {
"ABCDEFGHJKMNPQRSTUVWXYZ", // uppercase
"abcdefghjkmnpqrstuvwxyz", // lowercase
"23456789", // digits
"@#" // non-alphanumeric
};
string[] randomChars1 = new[] {
// uppercase
"abcdefghjkmnpqrstuvwxyz", // lowercase
"23456789", // digits
// non-alphanumeric
};
Random rand = new Random();
List<char> chars = new List<char>();
if (opts.RequireUppercase)
chars.Insert(rand.Next(0, chars.Count),
randomChars[0][rand.Next(0, randomChars[0].Length)]);
if (opts.RequireLowercase)
chars.Insert(rand.Next(0, chars.Count),
randomChars[1][rand.Next(0, randomChars[1].Length)]);
if (opts.RequireDigit)
chars.Insert(rand.Next(0, chars.Count),
randomChars[2][rand.Next(0, randomChars[2].Length)]);
if (opts.RequireNonAlphanumeric)
chars.Insert(rand.Next(0, chars.Count),
randomChars[3][rand.Next(0, randomChars[3].Length)]);
for (int i = chars.Count; i < opts.RequiredLength
|| chars.Distinct().Count() < opts.RequiredUniqueChars; i++)
{
string rcs = randomChars1[rand.Next(0, randomChars1.Length)];
chars.Insert(rand.Next(0, chars.Count),
rcs[rand.Next(0, rcs.Length)]);
}
return new string(chars.ToArray());
}
public static string GenerateRandomNumericPassword(int length = 8)
{
Random rand = new Random();
string password = "";
for (int i = 0; i < length; i++)
{
password += rand.Next(0, 10);
}
return password;
}
}
}