MD5哈希值与期望值不匹配

本文关键字:不匹配 期望值 哈希值 MD5 | 更新日期: 2023-09-27 18:09:55

我试图在c#中生成MD5哈希,但我无法检索我期望的字符串。

使用MD5哈希生成器,字符串Hello World!返回ed076287532e86365e841e92bfc50d8c的哈希值。

使用此代码:

string hash;
using (MD5 md5 = MD5.Create())
{
    hash = Encoding.UTF8.GetString(md5.ComputeHash(Encoding.Default.GetBytes("Hello World!")));
}

返回有问题的�'ab�S.�6^����'r�

我怀疑这是与我的字符串编码有关的问题。如何检索期望值?

Edit:正如您所看到的,我没有太多(任何)使用MD5哈希的经验-这个问题的目的是教育自己,而不是使用代码来保护信息。

MD5哈希值与期望值不匹配

ComputeHash()返回一个字节数组。使用一种方法将其转换为您想要的十六进制格式,例如BitConverter.ToString和一些字符串操作来摆脱连字符:

    string hash;
    using (MD5 md5 = MD5.Create())
    {
        hash = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes("Hello World!")));
    }
    hash = hash.Replace("-", "");

输出:ED076287532E86365E841E92BFC50D8C

ComputeHash()返回一个字节数组。您必须将该字节数组转换为十六进制表示法的字符串。

public string CalculateMD5Hash(string input)
{
        // step 1, calculate MD5 hash from input
        using(MD5 md5 = System.Security.Cryptography.MD5.Create())
        {
           byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
           byte[] hash = md5.ComputeHash(inputBytes);
           // step 2, convert byte array to hex string
           StringBuilder sb = new StringBuilder(2 * hash.Length);
           for (int i = 0; i < hash.Length; i++)
           {
              // use "x2" for all lower case.
              sb.Append(hash[i].ToString("X2"));
           }
           return sb.ToString();
        }
}

如果您希望哈希的string表示,则必须byte[]表示进行编码:

using System.Security.Cryptography;
...
public string MD5Hash(String input) {
  using (MD5 md5 = MD5.Create()) {
    return String.Concat(md5
      .ComputeHash(Encoding.UTF8.GetBytes(input))
      .Select(item => item.ToString("x2")));
  }
}
...
// hash == "ed076287532e86365e841e92bfc50d8c"
String hash = MD5Hash("Hello World!");