Welcome to the navigation

Cupidatat dolore amet, nisi proident, excepteur occaecat adipisicing ut dolore sit tempor non ut minim elit, ex velit sunt magna esse ipsum cillum ut enim. Irure eu qui esse proident, in sunt commodo incididunt pariatur, et ullamco dolore mollit dolor culpa nostrud cillum adipisicing ipsum sed ea reprehenderit labore fugiat

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! :)
Please note that this portal is a BETA site , I will continuously improve all functionality and performance during the coming weeks / the author