This is an update to my Simple Random Password Generator. It has been renamed to SecurePasswordGenerator and uses RandomNumberGenerator instead of using Random.
If you would like to view the original source, it can be found here.
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
public struct SecurePasswordGenerator(int PasswordLength, char[] LegalChars) : IEnumerable<char>
{
//was used for test purposes calling from a static method
//private readonly int PasswordLength => passwordLength;
public readonly string NextPassword() => new(this.ToArray());
public static IEnumerable<string> GeneratePasswords(int size, SecurePasswordGenerator generator) =>
generator.Chunk(size).Select(chunk => new string(chunk));
readonly IEnumerator<char> IEnumerable<char>.GetEnumerator()
{
bool isInvalidChars = LegalChars == null || LegalChars.Length == 0;
if (isInvalidChars || PasswordLength <= 0) yield break;
using RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[] buffer = new byte[PasswordLength * 4];
rng.GetBytes(buffer);
for (int i = 0; i < PasswordLength; i++)
{
int offset = i * 4;
uint rand = BitConverter.ToUInt32(buffer, offset);
yield return LegalChars![(int)(rand % LegalChars.Length)];
}
}
[DebuggerHidden, DebuggerStepThrough]
readonly IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}