Skip Navigation

MD5 hashing in .NET to match PHP

16 February 2006 10:39 by steve.temple

I had a bit of a struggle recently trying to get .NET to hash a string that would match PHPs built in MD5 hashing. Ended up that it was a string encoding issue, heres how I got it to work:

'--------------------------------------------------------------------
' Hash the string to match PHPs MD5
'--------------------------------------------------------------------

Private Function Hash(ByVal sValue As String) As String

Dim oTextBytes As Byte() =
System.Text.Encoding.ASCII.GetBytes(sValue)

Dim cryptHandler As
System.Security.Cryptography.MD5CryptoServiceProvider

cryptHandler = New System.Security.Cryptography.MD5CryptoServiceProvider

Dim oHash As Byte() = cryptHandler.ComputeHash(oTextBytes)

Return LCase(EncodeHexString(oHash))

End Function

'--------------------------------------------------------------------
' Encode the hex string to match PHP MD5
'--------------------------------------------------------------------
Public Function EncodeHexString(ByVal sArray As Byte()) as String

Dim sb As System.text.StringBuilder = New
System.text.StringBuilder(sArray.Length * 2)

Dim index As Integer

For index = 0 To sArray.Length - 1

sb.AppendFormat("{0:X2}",
sArray(index))

Next

Return sb.ToString()
End Function