A simple random password generator in C#. Looking for any improvements around speed or design. Any char[] can be passed to choose random chars from. The array I used for testing was a basic hex-only array
char[] hexChars = ['a', 'b', 'c', 'd', 'e', 'f',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
using System.Collections;
using System.Diagnostics;
public struct PasswordGenerator(int passwordLength, char[] legalChars) : IEnumerable<char>
{
private readonly int PasswordLength => passwordLength;
public readonly string Result => new(this.ToArray());
public static IEnumerable<string> GeneratePasswords(int size, PasswordGenerator
generator) => generator.Chunk(size).Select(chunk => new string(chunk));
/// <summary>
/// Creates a random password
/// </summary>
readonly IEnumerator<char> IEnumerable<char>.GetEnumerator()
{
long charsSupplied = 0;
bool isInvaidChars = legalChars == null || legalChars.Length == 0;
if(isInvaidChars || PasswordLength <= charsSupplied) yield break;
while(charsSupplied < PasswordLength)
{
yield return legalChars![Random.Shared
.Next(0, legalChars.Length)];
charsSupplied++;
}
}
[DebuggerHidden, DebuggerStepThrough]
readonly IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
Some example output using GeneratePasswords. The initial size of passwordLength = 256 & chunk size 16. produces a 16x16 array of random passwords.
dc97cf1446f444be
87c8317988a82970
8a39de9b17d4261c
bd0590ec321a63a9
c364b91598daa003
52e03dddab13f9a1
f4685739d2b2fe94
eef1cd9b14b379fd
f2f3b29e8c9ed0ba
def6b4bd66ba1c07
931d1e29268fa2c2
d7d3802effc2da19
26332c1388125e3c
1d81cbbc2b439577
1a1ff3b24c6d64fa
88d84617ccc0a434
System.Security.Cryptography.RandomNumberGeneratorfor password generation rather thanSystem.Random. Later this week I could provide a sample how to rewrite to it to make it more secure and performant. \$\endgroup\$