Click here to Skip to main content
15,880,469 members
Articles / Programming Languages / C#
Article

Build a class to generate random passwords

Rate me:
Please Sign up or sign in to vote.
1.73/5 (5 votes)
1 Apr 20054 min read 47.4K   635   20   4
An explanation of how to build a class in C# to generate random passwords.

Introduction

If you're anything like me, you must have come across situations where you need to generate a random password comprised of random alphanumeric and punctuation characters. While there are many tools out there that will do this for you, why not write a class in C# to do the same, especially when C# makes it so simple and easy.

First step

The first step is to create a class that will take in the properties that we would like to set for generating a random password(s). When I thought about how I'd like to generate passwords, there were several criteria that sprung to my mind:

  • Password length: how many characters long should the password be?
  • Include letters: will the password include letters? (a-z, A-Z)
  • Include mixed case: will the letters be of mixed case?
  • Include numbers: will the password include numbers? (0 - 9)
  • Include punctuation: will the password include punctuation characters?
  • No similar characters: will the password contain similar looking characters (0, O, l, i, !).
  • Quantity: how many passwords do we actually want to generate?

If you download and take a look at the Password class that I've supplied, you'll see that I've created a private internal variable for each one of these characteristics as well as a public property for each one. This will allow you to set the properties for the class after you've instantiated it.

Character pool

You'll notice another private internal variable that I have declared:

C#
private ArrayList marrCharPool;

This is the ArrayList that we are going to use to store a pool of individual characters that we will randomly choose from to build up our passwords.

Take a look at the main public method of this class called Generate() This is the method we call in the class to generate our passwords. It returns a carriage return delimited string of the passwords we choose to generate.

One of the first things this method does is start the random number generator:

C#
Random rdm = new Random();

The next thing the method does is call the private internal method BuildCharacterPool(). This method will populate our marrCharPool variable with the pool of characters we are going to use to build our passwords.

In BuildCharacterPool() we first clear the ArrayList in case it contains any characters already:

C#
marrCharPool.Clear();

If the mbIncludeLetters variable is set to true, then we know that we have to populate the character pool with all lowercase letters of the alphabet (a - z). But how can we do this without typing in each individual letter of the alphabet? Easy, we can use the Convert.ToChar(i).ToString() method to specify an ASCII code to retrieve the corresponding character. If you look at the ASCII codes of the characters you want from any ASCII table then you can easily specify which characters you want to add to the character pool.

In this case we want to add from ASCII code 97 to 122, which will give us all the lowercase alphabet letters:

C#
if (mbIncludeLetters == true)
{
    for (int i=97; i < 123; i++)
    {
        marrCharPool.Add(Convert.ToChar(i).ToString());
    }
}

This is a simple iteration from 97 to 122.

In this way we can check all the properties of the class to determine what characters should be added to the class:

C#
/*Add uppercase alphabet if required*/
if (mbIncludeMixedCase == true)
{
    for (int i=65; i < 91; i++)
    {
        marrCharPool.Add(Convert.ToChar(i).ToString());
    }
}

//add numbers if required
if (mbIncludeNumbers == true)
{
    for (int i=48; i < 58; i++)
    {
        marrCharPool.Add(Convert.ToChar(i).ToString());
    }
}

//add punctuation if required
if (mbIncludePunc == true)
{
    for (int i=33; i < 48; i++)
    {
        marrCharPool.Add(Convert.ToChar(i).ToString());
    }

    for (int i=58; i < 65; i++)
    {
        marrCharPool.Add(Convert.ToChar(i).ToString());
    }
}

//Remove similar characters if required
if (mbNoSimilarCharacters == true)
{
    string sValue = ConfigurationSettings.AppSettings["similarcharacters"];
    string [] a;

    a = sValue.Split(",".ToCharArray());

    for (int i=0;i<=a.GetUpperBound(0);i++)
    {
        marrCharPool.Remove(a[i].ToString());
    }
}

Once this has been done, we have a pool of characters stored in an ArrayList from which we can randomly select characters.

Returning the passwords

We can now move on to the next step in our Generate() method:

C#
//Iterate through the number of passwords required
for (int x=0; x < miQuantity; x++)
{
    //Iterate through the number of characters required in the password
    for (int i=0; i < miPasswordLength; i++)
    { 
        sResult += marrCharPool[rdm.Next(marrCharPool.Count)].ToString();
    }
    sResult = sResult + "\r\n";
}

Here we are iterating through the quantity of passwords specified in the Quantity property of our Password class. Within this loop is another iteration through the number of characters specified for our password(s) in the PasswordLength property. We build the individual passwords with this line:

C#
sResult += marrCharPool[rdm.Next(marrCharPool.Count)].ToString();

Here we are specifying a random index within the ArrayList to pull out a random character. The rdm.next(marrCharPool.Count) method returns a random integer from the total number of items contained in the ArrayList. Then with each iteration of the loop, we build up the sResult variable with our password, character by character. Within the Quantity loop we then separate each individual password with a carriage return "\r\n".

When both loops are finished we then return the result back to the function:

C#
return sResult;

This will contain the final carriage return-delimited list of passwords.

Conclusion

This is just a simple class for generating passwords. There are many future modifications I would like to make, specifically on returning passwords from the Generate() method. A more generic way to do this would be either to return the passwords back in an array, or perhaps in a more conventional comma-delimited fashion.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United Kingdom United Kingdom
David is originally from Cape Town in South Africa, but has been living and working in London for the past 3 years as a .NET developer for various new media design agencies.

Comments and Discussions

 
GeneralGreat job! Pin
takcrazy6-Mar-06 21:22
takcrazy6-Mar-06 21:22 
GeneralExtra challenge Pin
Jason Stangroome3-Apr-05 15:39
professionalJason Stangroome3-Apr-05 15:39 
Generalyes. but... Pin
mcarbenay2-Apr-05 5:03
mcarbenay2-Apr-05 5:03 
GeneralRe: yes. but... Pin
David Farrell3-Apr-05 22:48
David Farrell3-Apr-05 22:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.