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:
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:
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:
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:
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:
if (mbIncludeMixedCase == true)
{
for (int i=65; i < 91; i++)
{
marrCharPool.Add(Convert.ToChar(i).ToString());
}
}
if (mbIncludeNumbers == true)
{
for (int i=48; i < 58; i++)
{
marrCharPool.Add(Convert.ToChar(i).ToString());
}
}
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());
}
}
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:
for (int x=0; x < miQuantity; x++)
{
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:
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:
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.
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.