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