Tuesday, January 15, 2008

C# Password Generator

Simple, yet very effective password generator which i use for new users registration.


public static string Generate(int passwordLength)
{
string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789_";

Byte[] randomBytes = new Byte[passwordLength];
Random rGen = new Random();
rGen.NextBytes(randomBytes);

char[] chars = new char[passwordLength];
int allowedCharCount = _allowedChars.Length;

for (int i = 0; i < passwordLength; i++)
{
chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
}

return new string(chars);
}

No comments: