这个C#asp.net随机密码代码如何工作?

qua*_*els 1 c# asp.net random

我是.NET和C#的新手,我正在试图弄清楚这段代码是如何工作的:

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);
}
Run Code Online (Sandbox Code Playgroud)

我想大部分时间我都能很好地掌握它.我无法理解以下内容:

chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
Run Code Online (Sandbox Code Playgroud)

据我所知,代码生成随机二进制数,并在for循环中使用这些随机数从_allowedChars字符串中选择一个字符.我没有得到的是为什么这段代码使用modulous运算符(%)来获取_allowedChars索引值.

谢谢你的帮助

Joe*_*orn 5

这只是一个侧面说明,但该代码被巧妙地打破.用于选择要选择哪个字符的模数运算符(%)不是统一的:它会比其他字符更喜欢某些字符(比数组前面更接近的字符),这意味着密码不是真正随机的.攻击者可以使用它来首先尝试更高概率的密码,并显着减少完成破解所需的时间.