Created
October 25, 2023 10:40
-
-
Save alastair-todd/553f37139281634ab472e4da55dbcba3 to your computer and use it in GitHub Desktop.
C# Password Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class PasswordGenerator | |
{ | |
// https://stackoverflow.com/questions/65393858/force-the-password-to-contain-lower-case-upper-case-special-character-and-numb | |
private const string Uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
private const string Lowercase = "abcdefghijklmnopqrstuvwxyz"; | |
private const string Symbol = "!-_*+&$#@')(%"; | |
private const string Number = "0123456789"; | |
private static readonly Random Random = new (); | |
/// <summary> | |
/// 12 characters with at least 1 of each: symbol, number, uppercase and lowercase | |
/// </summary> | |
public static string CreateStrongPassword() => Create(12, Lowercase, Symbol, Number, Uppercase); | |
private static string Create(int length, params string[] keys) | |
{ | |
var chars = new char[length]; | |
for (int i = 0; i < keys.Length; i++) | |
{ | |
var key = keys[i]; | |
chars[i] = key[Random.Next(key.Length)]; | |
} | |
for (int i = keys.Length; i < length; i++) | |
{ | |
var indexKeys = Random.Next(keys.Length); | |
var key = keys[indexKeys]; | |
chars[i] = key[Random.Next(key.Length)]; | |
} | |
return new string(chars.OrderBy(x => Guid.NewGuid()).ToArray()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment