加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:49:28 所属栏目:百科 来源:网络整理
导读:我在检查C#和 PHP中的文件的MD5校验和方面遇到了一个小问题. PHP脚本计算的哈希值与C#计算的哈希值不同. libcurl.dll C# = c3506360ce8f42f10dc844e3ff6ed999libcurl.dll PHP = f02b47e41e9fa77909031bdef07532af 在PHP中我使用md5_file函数,我的C#代码是:
我在检查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);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读