Create a random strong password

This is to create a random strong password. I don’t want to make it too strong, for example password with special character. 1 number and 1 upper case will be sufficient.

There are a few good articles. I get the idea from these posts.

If you use ASP.Net 2, you can use System.Web.Security: MemberShip.GeneratePassword(…). This will be handy, readily available method. This password this method generate actually include special characters and punction letters such as (, {, ; :, and so on. This didn’t cause an issue to me, but in some cases like you want to generate DB connection string automatically, it will be a problem because ; will break it.

Anyway, the method wasn’t cool as I expected, and I wrote my own method. Well, it is not really my original one. I used a part of example codes from MSDN.

const string LOWERCASESET = "abcdefghijklmnopqrstuvwxyz";
const string NUMBERSET = "1234567890";
const int SALTLENGTH = 8;

public static string CreateNewPasswordSalt()
    return GeneratePasswordSet(SALTLENGTH, UPPERCASESET + NUMBERSET);

public static string GenerateRandomStrongPassword(int length, int numberOfUppercaseChar, int numberOfNumeric)
    return GeneratePasswordSet(numberOfUppercaseChar, UPPERCASESET) +
        GeneratePasswordSet(length - (numberOfUppercaseChar + numberOfNumeric), UPPERCASESET + LOWERCASESET + NUMBERSET) +
        GeneratePasswordSet(numberOfNumeric, NUMBERSET);

private static string GeneratePasswordSet(int length, string ALPHANUMERICSET)
    string password = string.Empty;
    int position;
    byte[] data = new byte[length];

    RandomNumberGenerator random = RandomNumberGenerator.Create();

    for (int i = 0; i < length; i++)
        position = (data[i] % ALPHANUMERICSET.Length);
        password = password + ALPHANUMERICSET.Substring(position, 1);
    return password;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s