Welcome to the navigation

Voluptate reprehenderit eiusmod velit in nisi elit, quis laborum, sint laboris adipisicing nulla minim id cillum magna dolor consequat, est consectetur dolore labore aute culpa. Voluptate adipisicing quis in exercitation laborum, ut et dolor ad sunt elit, irure sit ex commodo ipsum est ut duis fugiat ut nostrud mollit culpa

Yeah, this will be replaced... But please enjoy the search!

Creating a (very) random password generator in c#

Categories Tags

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! :)