How does this C# asp.net random password code work?
Posted
by quakkels
on Stack Overflow
See other posts from Stack Overflow
or by quakkels
Published on 2010-05-10T21:20:40Z
Indexed on
2010/05/10
21:24 UTC
Read the original article
Hit count: 347
Hello all,
I'm new to .NET and C# and I'm trying to figure out how this code works:
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++)
{
///
/// I don't understand how this line works:
///
chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
}
return new string(chars);
}
I think I've got a pretty good handle on most of this. I haven't been able to understand the following line:
chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
I understand that the code generates random binary numbers and uses those random numbers in the for loop to select a character from the _allowedChars string. What I don't get is why this code uses the modulous operator (%) to get the _allowedChars index value.
Thanks for any help
© Stack Overflow or respective owner