Trikks

The digital adventures of Eric Herlitz

Creating a (very) random password generator in c#

Posted by trikks on April 24, 2012

It’s not as hard as it seems. There are some things to think of but I’d like to say that this snippet will solve the most common issues of password generation. I also see a lot of questions on the net where the .net Random() doesn’t generate random numbers as it should. Well it does, the problem is that most peeps implement it inside some method which is bad. Declare it OUTSIDE the methods to get random working as it should, alright…

This little baby generates passwords like this
Stronger passwords (12 characters)
$te++3t0hWqa
*8ujWeqLno)b
:gX0zZb47Z)X

Simpler passwords (12 characters)
AcpO8g8UOK4R
oQbLmN2bodCP
CfORDnaNvwC2

Snippet

/// <summary>
/// Random declaration must be done outside the method to actually generate random numbers
/// </summary>
private static readonly Random Random = new Random();

/// <summary>
/// Generate passwords
/// </summary>
/// <param name="passwordLength"></param>
/// <param name="strongPassword"> </param>
/// <returns></returns>
private static string PasswordGenerator(int passwordLength, bool strongPassword)
{
    int seed = Random.Next(1, int.MaxValue);
    //const string allowedChars = "ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
    const string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
    const string specialCharacters = @"!#$%&'()*+,-./:;<=>?@[\]_";

    var chars = new char[passwordLength];
    var rd = new Random(seed);

    for (var i = 0 ; i < passwordLength; i++)
    {
        // If we are to use special characters
        if (strongPassword && i % Random.Next(3, passwordLength) == 0 )
        {
            chars[i] = specialCharacters[rd.Next(0 , specialCharacters.Length)];
        }
        else
        {
            chars[i] = allowedChars[rd.Next(0 , allowedChars.Length)];
        }
    }

    return new string(chars);
}

Cheers! :)

About these ads

2 Responses to “Creating a (very) random password generator in c#”

  1. Harsha Reddy said

    code worked like magic

  2. Peter said

    Thanks – really quick snipped of code to provide a good piece of functionality in password resetting, etc. +1

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: