How to Generate Random Passwords in C#

If you’re developing a site that requires users to logon, chances are you’re going to need to be able to generate passwords at some point, whether it be when users initially create their accounts or after they lose their passwords and need to reset their account credentials.

Here’s a very customizable function that will generate a pseudo-random password for you in C#

public static string GenerateRandomPassword(int Length)
{
char[] ValidCharacters = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
string password = string.Empty;
Random RndGenerator = new Random();
for (int i = 0; i < Length; i++)
{
int x = RndGenerator.Next(1, ValidCharacters.Length);
if (!password.Contains(ValidCharacters.GetValue(x).ToString()))
{
password += ValidCharacters.GetValue(x);
}
else
{
i--;
}
}
return password;
}

There’s some really neat stuff going on in this function.  You can specify which characters you would like to choose from as your random choices. It’s definitely better to have a longer array of choices, so if you’re comfortable putting in special characters like !, @, #, $, %, ^, &, or *, that will make it much harder for your passwords to be brute-forced or hacked otherwise.  The above function also makes sure that the same character isn’t used twice for additional security. You can take out the if-else statement if you’re not concerned about that.

To make use of the function, you can just call it up, specify the length of the password you would like to create and it will return a string that contains a random password of that length.

Happy Developing!

Comments

  1. I like this. A lot.

  2. you should store passwords in secure strings, not regular strings

  3. Nagaraju Rage says:

    It is a nice logic to generate random passwords.

Speak Your Mind

*