Jaslabs: High performance Software

High Performance Software

A PHP compatible MD5 function in c#

By Justin Silverton

The following is a function written in c# that will return a PHP compatible MD5 hash of a file, given the name. The equivalent function in PHP is md5_file().


public string MD5Hash( string sFilePath )
{
try
{
MD5CryptoServiceProvider md5Provider
= new MD5CryptoServiceProvider();
FileStream fs
= new FileStream(sFilePath, FileMode.Open, FileAccess.Read);
Byte[] hashCode
= md5Provider.ComputeHash(fs);

string ret = "";

foreach (byte a in hashCode)
{
if (a<16)
ret += "0" + a.ToString ("x");
else
ret += a.ToString ("x");
}

fs.Close();
return ret;
}
catch( Exception ex )
{
throw ex;
}
}

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati

3 Comments so far

  1. GolDen July 18th, 2007 4:30 pm

    The capability hasn’t completed yet, because the original function has an optional raw_output boolean parameter. Any way it’s good example of usage md5 api in c#. I’m interesting why you hasn’t wrote anything about c# before and write now?

  2. Justin Silverton July 18th, 2007 8:32 pm

    Thanks for the comment/suggestion.

    I have been using c# on a couple of personal projects in the past year and I recently had to create a windows application that communicated with a php web service (which also needed the md5_file() functions to match on both sides).

  3. GolDen July 23rd, 2007 4:10 am

    I hope to see other news about c# here, at least one reader is guaranteed for it ;)

Leave a reply