Welcome to the navigation

Cillum reprehenderit dolore mollit sit dolor tempor ipsum ullamco dolor veniam, sed ex minim ea aliqua, irure sunt pariatur, consequat, anim lorem deserunt esse in. Sint excepteur in sit anim labore exercitation dolor ipsum et irure eu tempor ullamco veniam, lorem proident, commodo cillum amet, reprehenderit pariatur, incididunt culpa sed

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)

Simpler passwords (12 characters)


/// <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)];
            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