Generating Random Passwords (with required characters) in c#

passwordIn looking for a way to create some passwords that included sets of characters (lower case, upper, numbers or symbols) below is a chunk of code that seems to do the job. It makes use of RNGCryptoServiceProvider from System.Security.Cryptography instead of the classic Random.

You can choose a set length or variable:

//use a set length
string pass = GenerateAPassword(10);

//or get a random length between two ints
string pass = GenerateAPassword(12, 15);

The required parts of the password are created using a simple string array. -Be careful is creating small sets of strings, as it could take longer to create a password to fulfill the requirements.

 string[] parts = new string[] { "abcdefghjkmnpqrstuvwxyz", "ABCDEFGHJKLMNPQRSTUVWXYZ", "23456789", "*&^%$#@!" };


Below is the needed code.

You’ll need: using System.Security.Cryptography & using System.Text at the least.

public string GenerateAPassword(int length, int maxl = 0)
            //separate required parts of password below
            //below i have lower, upper, numbers and symbols
            string[] parts = new string[] { "abcdefghjkmnpqrstuvwxyz", "ABCDEFGHJKLMNPQRSTUVWXYZ", "23456789", "*&^%$#@!" };

            if (length < parts.Length + 1)
                return "invalid length";

            if (maxl > 0)
                length = rngNumber(length, maxl);

            StringBuilder pass = new StringBuilder();
            int l = length;
            while (0 < l--)
                pass.Append(string.Join("", parts)[rngNumber(0, string.Join("", parts).Length - 1)]);

            //check of parts of password exist
            foreach (string part in parts)
                if (pass.ToString().IndexOfAny(part.ToCharArray()) == -1)
                    //create again if missing
                    return GenerateAPassword(length);

            return pass.ToString();

        private static readonly RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        public static int rngNumber(int min, int max)
            byte[] randomNumber = new byte[1];


            return (int)(min + (Math.Floor(Math.Max(0, ((Convert.ToDouble(randomNumber[0])) / 255d) - 0.00000000001d) * (max - min + 1))));


Generating Random Passwords (with required characters) in c#

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s