c# - C# 和 PHP 中的不同 MD5 文件哈希

标签 c# php encoding md5 checksum

我在检查 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();
}

任何想法如何计算相同的散列?我认为这可能与编码有关。

提前致谢!

最佳答案

我的 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);

我不确定它是否真的按原样运行,但我认为需要一些类似的东西。

关于c# - C# 和 PHP 中的不同 MD5 文件哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15705676/

相关文章:

c# - 连接Godaddy mysql服务器时出现错误

c# - 将字节数组转换为 16 位 float

php - 将数组插入查询,然后将结果循环到新查询中

php - DOCX 编码问题

encoding - 有没有什么好方法可以将 "encode"二进制数据视为合理的组合词并再次返回?

c# - 将 Word DOCX 文件保存为 PDF

c# - 扩展和过滤 C# 数组

php - 在php中重复数组日期

PHP在for循环中嵌套for循环

encoding - 在 Haxe 中使用 sys.io.File.read 读取文件时指定文件编码