[英]Different MD5 file hash in C# and PHP
I have a small problem in checking MD5 checksum of files in C# and PHP. 我在检查C#和PHP中的文件的MD5校验和方面遇到了一个小问题。 The hash calculated by PHP script vary from hash calculated by C#. PHP脚本计算的哈希值与C#计算的哈希值不同。
libcurl.dll C# = c3506360ce8f42f10dc844e3ff6ed999
libcurl.dll PHP = f02b47e41e9fa77909031bdef07532af
In PHP I use md5_file
function, and my C# code is: 在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();
}
Any ideas how to calculate the same hash? 任何想法如何计算相同的哈希? I think that it may be something about encoding. 我认为这可能与编码有关。
Thanks in advance! 提前致谢!
My C# is rusty, but will: 我的C#生锈了,但会:
byte[] retVal = md5.ComputeHash(file);
actually read in the entire file? 实际读入整个文件? I think it is just hashing the stream object. 我认为它只是哈希流对象。 I believe you need to read the stream, then hash on the entire file contents? 我相信你需要读取流,然后哈希整个文件内容?
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);
I'm not sure if that actually runs as is, but I think something along those lines will be needed. 我不确定它是否真的按原样运行,但我认为需要沿着这些方向运行。
I use this: 我用这个:
I havent had yet any issues with comparison of php md5 with c# md5 我还没有将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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.