Skip to content

Instantly share code, notes, and snippets.

@alastair-todd
Created October 25, 2023 10:40
Show Gist options
  • Save alastair-todd/553f37139281634ab472e4da55dbcba3 to your computer and use it in GitHub Desktop.
Save alastair-todd/553f37139281634ab472e4da55dbcba3 to your computer and use it in GitHub Desktop.
C# Password Generator
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