Just Code‎ > ‎

C# Create Random Password with select set of available characters

posted Aug 27, 2009, 10:34 AM by Peter Henell   [ updated Aug 27, 2009, 11:11 AM ]
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
Comments