Strong random password generator C# Source code

If you need to generate a bulk amount of passwords you can use one of the widely available website passwordgenerator, use your won generator program, or if you don't trust anyone, you can quickly write your own program. Below is the source code of a True Random password generator written entirely in C#. Compared to similar programs available on the net, which use clock-dependent C# System.Random Number Generator, this code sample uses RNGCryptoServiceProvider which is far more secure and provides unique numbers over a long period of time. Even if you won't notice the difference in generating 1-2 passwords, the RNGCryptoServiceProvider will have more even distribution for thousands of iterations.

Let's get closer to the code. The user enters the number of generated passwords and the length of passwords. Also, the available character sets are specified inside the code.


namespace SecureRandomPassword
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    public class RandomPassword
    {
        private static readonly RNGCryptoServiceProvider provider = new();
        public static List GetRandomPassword(int size = 12, int count = 1)
        {
            List randomPassword = new();
            // Set required letters
            string CapitalLetters = "QWERTYUIOPASDFGHJKLZXCVBNM";
            string SmallLetters = "qwertyuiopasdfghjklzxcvbnm";
            string Digits = "0123456789";
            string SpecialCharacters = "!@#$%^&*()-_=+<,>.";
            string AllChar = CapitalLetters + SmallLetters + Digits + SpecialCharacters;
            string[] AllPasswords = new string[count];
            for (int i = 0; i < count; i++)
            {
                StringBuilder sb = new();
                for (int n = 0; n < size; n++)
                {
                    sb = sb.Append(GenerateChar(AllChar));
                }
                AllPasswords[i] = sb.ToString();
            }
            foreach (var singlePassword in AllPasswords)
            {
                randomPassword.Add(singlePassword);
            }
            return randomPassword;
        }
        private static char GenerateChar(string availableChars)
        {
            var byteArray = new byte[1];
            char c;
            do
            {
                provider.GetBytes(byteArray);
                c = (char)byteArray[0];
            } while (!availableChars.Any(x => x == c));
            return c;
        }
    }
}

Just copy past the code and use it.


Summary: