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

我不确定它是否实际运行,但我认为需要一些类似的东西。

我用这个:

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

相关内容

最新更新