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.
74 lines
2.6 KiB
74 lines
2.6 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace Common.Helper
|
|
{
|
|
public 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());
|
|
}
|
|
}
|
|
}
|