public static string GenerateRandomPassword(int length)
{
if (length < 6) throw new ArgumentException("length must be at least 6.");
StringBuilder pass = new StringBuilder();
// Temporary array containing our character set:
// uppercase letters, lowercase letters, and digits
char[] charSet = new char[62];
for( int i = 0; i < 26; i++) charSet[i] = (char)('A' + i); // Uppercase letters
for( int i = 26; i < 52; i++) charSet[i] = (char)('a' + i - 26); // Lowercase letters
for( int i = 52; i < 62; i++) charSet[i] = (char)('0' + i - 52); // Digits
// We generate two of each character class.
pass.Append(charSet[randGen.Next(0,26)]); // uppercase
pass.Append(charSet[randGen.Next(0, 26)]); // uppercase
pass.Append(charSet[randGen.Next(26, 52)]); // lowercase
pass.Append(charSet[randGen.Next(26, 52)]); // lowercase
pass.Append(charSet[randGen.Next(52,62)]); // digit
pass.Append(charSet[randGen.Next(52,62)]); // digit
// The rest of the password is randomly generated from the full character set
for (int i = pass.Length; i < length; i++ )
{
pass.Append(charSet[randGen.Next(0, charSet.Length)]);
}
// Shuffle the password using the Fisher-Yates random permutation technique
for (int i = 0; i < pass.Length; i++ )
{
int j = randGen.Next(i, pass.Length);
// Swap i and j
char tmp = pass[i];
pass[i] = pass[j];
pass[j] = tmp;
}
return pass.ToString();
}