哈希函数.NET

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

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

谢谢

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

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

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