哈希函数.NET

时间:2011-03-07 07:14:13

标签: c# .net hash hashcode

  

可能重复:
  Hash Function .NET

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

我看到.NET框架建议了几个哈希函数,我不知道要使用什么, 有没有人告诉我什么是最好的功能使用,如何将输出限制为22个字符(在base64上)?

谢谢

1 个答案:

答案 0 :(得分:4)

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