哈希函数.NET

时间:2011-03-07 06:51:50

标签: c# hash hashcode

我应该编写一个采用字符串输入并计算字符串哈希值的应用程序(输入的最大字符数为16),输出的长度应为base64格式的22个字符(或更少但不多)

我看到.NET框架提出了许多哈希函数,我不知道要使用什么, 任何人都可以推荐我使用的最佳功能,如何将输出限制为22个字符?

谢谢

3 个答案:

答案 0 :(得分:6)

您可以使用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);
}

答案 1 :(得分:3)

您可以使用任何散列函数,只需将散列截断为所需大小,然后转换为base-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);

答案 2 :(得分:1)

22个base64字符表示哈希函数的16字节输出;你可以使用输出128位的任何哈希函数。