2013-03-18 38 views
4

我使用Rfc2898DeriveBytes哈希密码。密码哈希通过Rfc2898DeriveBytes - 什么传递给getBytes

但是我不确定要传递给GetBytes方法,它需要一个int。

我应该传递什么样的价值?为什么?

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

回答

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 

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

+0

FWIW,StackExchange OpenID提供程序使用PBKDF2生成24个字节的安全哈希 - https://code.google.com/p/stackid/source/browse/OpenIdProvider/Current.cs – 2013-03-18 17:29:17