Generating Passwords

We have the requirement that our passwords have to change every 90 days.  I wanted to automate this and it sounded pretty easy to do, but it wasn’t that easy.  Why? Because there are a lot of rules for passwords.

First, I have to store it in the web.config.  So no XML special characters.

  1. quot "
  2. amp &
  3. apos ‘
  4. lt <
  5. gt >

Next, If used in an OLE DB or ODBC connection string, a password must not contain the following characters: [] {}() , ; ? * ! @.

Finally, strong passwords must contains characters from at least three of the following categories:

  1. English uppercase characters (A through Z)
  2. English lowercase characters (a through z)
  3. Base 10 digits (0 through 9) 
  4. Nonalphabetic characters (for example: !, $, #, %)

So keeping all of these rules in mind I created a simple class. that I can just call

public class PasswordGenerator

{

    private static string CHARS_LCASE = "abcdefgijkmnopqrstwxyz";

    private static string CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";

    private static string CHARS_NUMERIC = "23456789";

    private static string CHARS_SPECIAL = "*-+_%/";

    private static string CHARS_ALL = CHARS_LCASE + CHARS_UCASE + CHARS_NUMERIC + CHARS_SPECIAL;

 

    public static string GeneratePassword(int length)

    {

        char[] chars = new char[length];

        Random rand = new Random();

 

        for (int i = 0; i < length; i++)

        {

            switch (i)

            {

                case 0:

                    chars[i] = CHARS_LCASE[rand.Next(0, CHARS_LCASE.Length)];

                    break;

                case 1:

                    chars[i] = CHARS_UCASE[rand.Next(0, CHARS_UCASE.Length)];

                    break;

                case 2:

                    chars[i] = CHARS_NUMERIC[rand.Next(0, CHARS_NUMERIC.Length)];

                    break;

                case 3:

                    chars[i] = CHARS_SPECIAL[rand.Next(0, CHARS_SPECIAL.Length)];

                    break;

 

                default:

                    chars[i] = CHARS_ALL[rand.Next(0, CHARS_ALL.Length)];

                    break;

            }

        }

 

        return new string(chars);

    }

}

So now I just simply call this for a new password:

PasswordGenerator.GeneratePassword(13)

Leave a Comment

Your email address will not be published. Required fields are marked *