9

我正在使用 Rfc2898DeriveBytes 来散列密码。

但是,我不确定将什么传递给需要 int 的 GetBytes 方法。

我应该传递什么价值,为什么?

   Rfc2898DeriveBytes hasher = new Rfc2898DeriveBytes(password, System.Text.Encoding.Default.GetBytes(salt), PasswordHasher.Iterations);
      return Convert.ToBase64String(hasher.GetBytes(100));
4

1 回答 1

7

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.getbytes.aspx中所述,GetBytes 的参数是您希望 GetBytes 方法为您生成的字节数。如果您想要 5 个字节,则传递 5。如果您想要 500,则传递 500。您要求的字节数通常取决于您要生成的密钥(或其他加密输入)的预期用途所需的字节数。

为了更好地理解输出,请尝试运行以下命令行应用程序:

internal static class Program
{
    private static void Main()
    {
        var deriver = new Rfc2898DeriveBytes("apples and oranges", 100, 20);
        Program.WriteArray(deriver, 5);
        Program.WriteArray(deriver, 10);
        Program.WriteArray(deriver, 20);

        Console.ReadLine();
    }

    private static void WriteArray(Rfc2898DeriveBytes source, int count)
    {
        source.Reset();
        Console.WriteLine(string.Join(" ", source.GetBytes(count).Select(b => b.ToString())));
    }
}

输出应如下所示:

208 194 113 91 125
208 194 113 91 125 157 138 234 20 151
208 194 113 91 125 157 138 234 20 151 159 151 23 94 11 210 38 101 186 143

本质上,您将获得一个一致的字节列表(基于密码、盐和迭代),无论您选择什么长度。您可以随时从相同的输入重新生成完全相同的字节列表。

于 2013-03-18T17:22:04.963 回答