Categories: .Net Core 3

Random Password Generator In C#

I've previously talked about hashing a password for IdentitySever4 in C#. This works well when you want to store your password with added salt to a database or similar store that could be read.

In this previous article I talked about how this could be added to code that was bulk transferring users from one, older, user table to the new AspNetUsers in IdentityServer4. I also mentioned that when doing this you could also create a Random Password Generator to create initial passwords for those users.

In this article I am going to list a code example that does just this. It allows you to specify inputs to increase the character set to choose from. It also allows you to specify a size you would like that password to be (I would suggest at least 10 characters for security).

There are improvements you could make to this code: for example adding spaces, and making sure there are no more than 1 or 2 character that are consecutive (although in my tests is mostly random for each character in password). You could also add some validation to the password - something I may add examples for.

The random password generator C# code example

Let us start with the C# code example

First, lets define the random password generation code 

using System;

namespace PasswordGenerator
{
  class RandomPasswordGenerator
{

   const string LOWER_CASE = "abcdefghijklmnopqursuvwxyz";
   const string UPPER_CAES = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   const string NUMBERS = "123456789";
   const string SPECIALS = @"!@£$%^&*()#€";


    public string GeneratePassword(bool useLowercase, bool useUppercase, bool useNumbers, bool useSpecial,
        int passwordSize)
    {
        char[] _password = new char[passwordSize];
        string charSet = ""; // Initialise to blank
        System.Random _random = new Random();
        int counter;

        // Build up the character set to choose from
        if (useLowercase) charSet += LOWER_CASE;

        if (useUppercase) charSet += UPPER_CAES;

        if (useNumbers) charSet += NUMBERS;

        if (useSpecial) charSet += SPECIALS;

        for (counter = 0; counter < passwordSize; counter++)
        {
            _password[counter] = charSet[_random.Next(charSet.Length - 1)];
        }

        return String.Join(null, _password);
    }
  }
}

Breaking down this code. To begin with we create and set up some constant strings. These strings contain all the lowercase characters, uppercase characters, numbers and special characters. These are what we will be using for the password generation.

Next we define the GeneratePassword methods. We need to pass in parameters that define how we will generate the password.

In the case of this methods we pass in either True or False to say if using lowercase, uppercase, special or number characters to generate the password. The final input is the size of the password we want to generate.

Next we set up a few variables and objects we are going to be using through the method including the character set, and password string, a randomiser and a counter.

The next few lines simply adds characters to the character set to be used for the random password: depending on the input values to the method.

The final stage is to loop a number of times equal to the size of the password required and to pull out a random character from the character set, which is then added to the password.

This then gets returned to the calling method.

An example of how to call the password generator method

To call this class and generate a random password, you need to call with the following

static void Main(string[] args)
{
  string password;

  RandomPasswordGenerator randomPasswordGenerator = new RandomPasswordGenerator();

  password = randomPasswordGenerator.GeneratePassword(true, true, true, true, 16);
  Console.WriteLine(password);
}

You can see in this case we pass in true for all values and have a password size of 16.

Adding spaces to the password

If you wanted to be able to include spaces in your random password: you could add the following code.

First we need to add the new constant for space.

const string SPACE_CHARACTER = " ";

Next, we need to change the method to allow True/False to add spaces to the password.

public string GeneratePassword(bool useLowercase, bool useUppercase, bool useNumbers, bool useSpecial, bool addSpace, int passwordSize)

Finally we just need to add the extra True/False value to the method call.

password = randomPasswordGenerator.GeneratePassword(true, true, true, true, 16);

Ways to extend this functionality

There are more ways you could extend the functionality of this object. You could add a new method to ValidatePassword using Regex to check if it has a member of each of the characters you chose for the password.

You could add a method to check for same character next to each other (Hint: It could look like this) 

const int MAXIMUM_IDENTICAL_CONSECUTIVE_CHARS = 2
bool moreThanTwoIdenticalInARow =
 characterPosition > MAXIMUM_IDENTICAL_CONSECUTIVE_CHARS
 && _password[counter] == _password[counter - 1]
 && _password[counter - 1] == _password[cunter - 2];

if (moreThanTwoIdenticalInARow)
{
  characterPosition--;
}

These are just a few extras to improve the passwords you generate.

This code will give you random passwords

Using this method you will be able to generate a random password for a number of users. You could have this as a random password generator for when someone signs up. You could use it when doing something like a bulk user transfer.

What ever you need a random password generator for - this will hopefully suite your needs.

Sean

View Comments

  • This method does not guarantee that numbers are present in the password if includeNumbers = true.

    Same goes for includeSpecials and uppercase characters.

    There likely will be but, especially with smaller passwords, there is no guarantee.

    To fix this, you'l have to check whether the generated contains all of the requested character types, and re-generate if not.

    Considering the use of RNGCryptoServiceProvider: I cannot see a reason why using that class would improve on the quality of the chosen passwords.

    In full .net framework, the seed is time-dependend which requires at least 15 ms between Random instantiation to guarantee a different sequence of (pseudo) random numbers

    In .NET Core, that behaviour does not apply.

    Furthermore. The Random number generator isn't thread safe so make sure you serialize calls to Random.Next(...)

Recent Posts

What Is The Difference Between A Singleton Class And Dependency Injection

A singleton class is a design pattern where only one instance of a class can…

1 year ago

Dependency Injection In Java Explained With Code Example

As one of the most popular programming languages, Java has played a vital role in…

1 year ago

Are There So Many Bad C/C++ Developers Out There Today?

I was taking a look at Quora, something I try to do daily, and while…

1 year ago

Why I Deleted Windows And Installed Only Linux

I finally did it, I completely deleted Windows from my Laptop and installed Linux.  Let…

1 year ago

Why Are Graphics Cards So Expensive At The Moment?

Recently I've been building a new mid-level gaming system for my daughter, and although most…

3 years ago

How to balance work and family life

In order to balance work and family life, one must find the right work-life balance…

3 years ago