C#和PHP中MD5文件哈希值不同

4

我在使用C#和PHP检查文件的MD5校验和时遇到了小问题。通过PHP脚本计算出的哈希值与C#计算出的哈希值不同。

libcurl.dll C#   = c3506360ce8f42f10dc844e3ff6ed999
libcurl.dll PHP  = f02b47e41e9fa77909031bdef07532af

在 PHP 中我使用 md5_file 函数,我的 C# 代码如下:

protected string GetFileMD5(string fileName)
{
    FileStream file = new FileStream(fileName, FileMode.Open);
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] retVal = md5.ComputeHash(file);
    file.Close();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < retVal.Length; i++)
    {
        sb.Append(retVal[i].ToString("x2"));
    }
    return sb.ToString();
}

有什么想法可以计算相同的哈希值吗?我认为这可能与编码有关。

提前感谢!


2
我敢打赌,C# 使用 Windows-1250 编码,而你的 PHP 脚本使用 UTF-8ISO-8859-1 编码... 尝试在两侧使用相同的编码方式... - shadyyx
它与命令行工具md5sum相比如何? - Ja͢ck
使用FileStream时,您不能确定指针是否在开头。使用file.Seek(0, SeekOrigin.Begin)确保正确性。MSDN中的所有示例都在FileStream构造函数之后使用它。 - Xaruth
@Jack md5sum 返回 d41d8cd98f00b204e9800998ecf8427e,但有点奇怪,因为它与 md5("") 相同。 - Kacper
@shadyyx PHP并不使用任何编码,PHP中的字符串与byte[]相同,因此PHP无需解码。 - Esailija
@Kacper,你确定你确实在对同一个文件进行哈希处理吗?我使用你的代码,在PHP和C#中得到了相同的哈希值。 - Esailija
2个回答

1

我的C#生疏了,但是会:

byte[] retVal = md5.ComputeHash(file);

实际上,只是对流对象进行哈希处理吗?我认为需要先读取流,然后对整个文件内容进行哈希处理。
  int length = (int)file.Length;  // get file length
  buffer = new byte[length];      // create buffer
  int count;                      // actual number of bytes read
  int sum = 0;                    // total number of bytes read

  // read until Read method returns 0 (end of the stream has been reached)
  while ((count = file.Read(buffer, sum, length - sum)) > 0)
      sum += count;  // sum is a buffer offset for next reading
  byte[] retVal = md5.ComputeHash(buffer);

我不确定这段代码能否直接运行,但我认为需要类似的代码。


它产生的结果与使用ComputeHash相同。 - Kacper

0

我使用这个:

到目前为止,我还没有遇到过将php md5与c# md5进行比较的任何问题。

System.Text.UTF8Encoding text = new System.Text.UTF8Encoding();
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();                
Convert2.ToBase16(md5.ComputeHash(text.GetBytes(encPassString + sess)));


class Convert2
{
   public static string ToBase16(byte[] input)
   {
      return string.Concat((from x in input select x.ToString("x2")).ToArray());
   }
}

这是关于文件MD5吗?还是只是文本? - Kacper
不需要将文件解码为文本以获取MD5。如果它不是UTF-8呢? - Esailija

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接