Easy Password Generator: Create Secure Passwords in ASP.NET

Introduction

What we are going to make today is a password generator. It's really simple but can be quite simple but could come and handy someday. For example, I use it in Asp.Net if people register on my site I give them a randomly generated password so that people have to give their real e-mail address.

Open a new project like you always add a new class to the project name the class PassGen or whatever you want the class to be called.

We only need one namespace (Yeah! Life can be easy some days) System.

We need two things,

protected Random rGen;
protected string[] strCharacters = {
    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
    "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4",
    "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i",
    "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
};

You have to put this in the Constructor

public PassGen()
{
    rGen = new Random();
}

rGen provides us with a randomly generated number and strcharacters has all characters we need in an array.

Now we will make two methods one for generating a password that has only lowercase numbers and characters and one that makes both lowercase and uppercase characters.

public string GenPassLowercase(int i)
{
    int p = 0;
    string strPass = "";

    for (int x = 0; x <= i; x++)
    {
        p = rGen.Next(0, 35);
        strPass += strCharacters[p];
    }

    return strPass.ToLower();
}

And one for both upper/lowercase characters.

public string GenPassWithCap(int i)
{
    int p = 0;
    string strPass = "";
    for (int x = 0; x <= i; x++)
    {
        p = rGen.Next(0, 60);
        strPass += strCharacters[p];
    }
    return strPass;
}

As you may notice the integer let us choose how many characters we want in our password. Ok, that was quite easy and I think there was nothing that could cause a problem. Hope it will be of some value to you.


Similar Articles