Various MD5 hash files in C # and PHP

I have a little problem while checking the checksum of MD5 files in C # and PHP. The hash computed by the PHP script changes from the hash computed from C #.

libcurl.dll C# = c3506360ce8f42f10dc844e3ff6ed999 libcurl.dll PHP = f02b47e41e9fa77909031bdef07532af 

In PHP, I use the md5_file function, and my C # code:

 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 it could be something like coding.

Thanks in advance!

+4
source share
2 answers

My C # is rusty, but will be:

 byte[] retVal = md5.ComputeHash(file); 

really read in the whole file? I think this is just hashing a stream object. I believe you need to read the stream and then the hash to the whole 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); 

I'm not sure if this really works as it is, but I think something along these lines will be necessary.

+1
source

I use this:

I have not had problems comparing php md5 with C # md5 yet

 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()); } } 
0
source

All Articles