C# - MD5 哈希值与预期值不匹配

C# - MD5 hash not matching expected value

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

使用 MD5 Hash Generator,字符串 Hello World! returns ed076287532e86365e841e92bfc50d8c.

的散列

使用此代码:

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

returns �\ab�S.�6^����\r� 有问题。

我怀疑这与我对字符串的编码有关。如何检索预期值?

编辑:如您所见,我没有太多(任何)使用 MD5 哈希的经验 - 这个问题的目的是自学,而不是使用保护信息的代码。

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

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();
        }
}

ComputeHash() returns 字节数组。使用一种方法将其转换为所需的十六进制格式,例如BitConverter.ToString 和一些字符串操作来去掉连字符:

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

输出:ED076287532E86365E841E92BFC50D8C

如果您想要 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!");