MD5 hashing in .NET to match PHP

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.

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 value As String) As String
Dim textBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(value)
Dim cryptHandler As System.Security.Cryptography.MD5CryptoServiceProvidercryptHandler = New System.Security.Cryptography.MD5CryptoServiceProvider
Dim hash As Byte() = cryptHandler.ComputeHash(textBytes)
Return LCase(EncodeHexString(hash))
End Function

'---------------------------------------
' Encode the hex string to match PHP MD5
'---------------------------------------
Public Function EncodeHexString(ByVal array As Byte()) as String
Dim sb As System.text.StringBuilder = New System.text.StringBuilder(array.Length * 2)
Dim index As Integer
For index = 0 To sArray.Length - 1
sb.AppendFormat("{0:X2}", array(index))
Next
Return sb.ToString()
End Function

 

About the Author

Steve Temple, Technical Director and co-founder of Gibe

Steve is Gibe's technical director and super brain behind the development of our major projects. With over 28 years of commercial experience, Steve is an expert in .NET, Umbraco and Microsoft technologies. Steve is also an Umbraco Certified Master and Microsoft MCSD