2013-03-18 44 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