-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathPasswordGenerator.cs
60 lines (53 loc) · 2.24 KB
/
PasswordGenerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Linq;
namespace Ryadel.Components.Security
{
public static class PasswordGenerator
{
/// <summary>
/// Generates a Random Password
/// respecting the given strength requirements.
/// </summary>
/// <param name="opts">A valid PasswordOptions object
/// containing the password strength requirements.</param>
/// <returns>A random password</returns>
public static string Generate(
int requiredLength = 8,
int requiredUniqueChars = 4,
bool requireDigit = true,
bool requireLowercase = true,
bool requireNonAlphanumeric = true,
bool requireUppercase = true)
{
string[] randomChars = new[] {
"ABCDEFGHJKLMNOPQRSTUVWXYZ", // uppercase
"abcdefghijkmnopqrstuvwxyz", // lowercase
"0123456789", // digits
"!@$?_-" // non-alphanumeric
};
CryptoRandom rand = new CryptoRandom();
List<char> chars = new List<char>();
if (requireUppercase)
chars.Insert(rand.Next(0, chars.Count),
randomChars[0][rand.Next(0, randomChars[0].Length)]);
if (requireLowercase)
chars.Insert(rand.Next(0, chars.Count),
randomChars[1][rand.Next(0, randomChars[1].Length)]);
if (requireDigit)
chars.Insert(rand.Next(0, chars.Count),
randomChars[2][rand.Next(0, randomChars[2].Length)]);
if (requireNonAlphanumeric)
chars.Insert(rand.Next(0, chars.Count),
randomChars[3][rand.Next(0, randomChars[3].Length)]);
for (int i = chars.Count; i < requiredLength
|| chars.Distinct().Count() < requiredUniqueChars; 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());
}
}
}