C# Create Random Password with select set of available characters

Post date: Aug 27, 2009 5:34:46 PM

public static string CreateRandomPassword(int PasswordLength)

{

String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789";

Byte[] randomBytes = new Byte[PasswordLength];

RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

rng.GetBytes(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);

}

// Credits

// http://www.aspheute.com/english/20040105.asp