2011-03-07 90 views
2

我應該編寫一個應用程序,它接受字符串輸入並計算字符串的散列值(輸入的最大字符數爲16),輸出的長度應爲22個字符(或更少但不多於)在base64格式。散列函數.NET

我看到.NET框架提出了許多散列函數,我不知道該用什麼, 任何人都可以請推薦我什麼是最好的函數使用,以及如何限制輸出爲22個字符?

感謝

+1

你打算使用散列函數爲加密目的或散列表? – Ani 2011-03-07 06:55:13

+0

@Ani:22個字節的base64輸出表示加密散列函數,而不是散列表(通常使用機器字大小散列)。 – 2011-03-07 07:33:53

+0

MD5 [Link] [1]和SHA-1不再安全。 轉到爲SHA-2或SHA-3 [1]:http://security.stackexchange.com/questions/19906/is-md5-considered-insecure – user1849818 2014-10-06 18:18:14

回答

5

您可以使用MD5提供128位輸出,然後在轉換爲base64時丟棄最後兩個字符,因爲它們將始終爲「==」(填充)。這應該給你22個字符。

string GetEncodedHash(string password, string salt) 
{ 
    MD5 md5 = new MD5CryptoServiceProvider(); 
    byte [] digest = md5.ComputeHash(Encoding.UTF8.GetBytes(password + salt); 
    string base64digest = Convert.ToBase64String(digest, 0, digest.Length); 
    return base64digest.Substring(0, base64digest.Length-2); 
} 
2

你可以使用任何的散列函數的,只是截斷散列到所需的大小,然後轉換爲基於64位。在你的情況下,你需要截斷散列爲15個字節,最終爲20個字節的base-64。我將重用我之前的例子。

string secretKey = "MySecretKey"; 
string salt = "123"; 
System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create(); 
byte[] preHash = System.Text.Encoding.UTF32.GetBytes(secretKey + salt); 
byte[] hash = sha.ComputeHash(preHash); 
string password = prefix + System.Convert.ToBase64String(hash, 0, 15); 
1

22 base64字符表示散列函數的一個16字節輸出;你可以使用任何輸出128位的散列函數。