微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我不确定它是否真的按原样运行,但我认为需要沿着这些方向运行.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐