65.9K
CodeProject is changing. Read more.
Home

An MD5 Function Compatible with PHP

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (12 votes)

Jul 14, 2005

viewsIcon

97795

Describes an implementation of a MD5 function compatible with the PHP function.

Introduction

Recently I needed to integrate an ASP.NET application with SugarCRM, an Open Source CRM implementation (a very good one).

SugarCRM publishes a SOAP API, but I needed to send the password in MD5 format compatible with the MD5 function of PHP (SugarCRM is built on PHP). So I wrote a function that emulates the MD5 function of PHP.

MD5 Function

In PHP the MD5 function receives a string and returns a hexadecimal number of length 32.

So the implementation of this function in C# is like this:

using System.Security.Cryptography;
using System.Text;

public sealed class PhpCompatible
{
   public static string Md5Hash (string pass)
   {
     MD5 md5 = MD5CryptoServiceProvider.Create ();
     byte[] dataMd5 = md5.ComputeHash (Encoding.Default.GetBytes (pass));
     StringBuilder sb = new StringBuilder();
     for (int i = 0; i < dataMd5.Length; i++)
       sb.AppendFormat("{0:x2}", dataMd5[i]);
     return sb.ToString ();
}

One difficulty I found is with the AppendFormat, because I needed to pad the hexadecimal digit with 0. The solution was to put a 2 after the x of the format string. In general the documentation of the Format functions is hard to understand.

There are a lot of PHP applications out there, and we need to have a mechanism to interact with them. I hope this function helps you if you are in a situation like the one I described.