MD5 Problem

Martin

Newcomer
Joined
Jul 1, 2003
Messages
16
I have used a function to MD5 hash a password, however, the results are not correct:

Correct Result--> a985c9764e0e6d738ff20f2328a0644b
My Result --> a985c9764ee6d738ff2f2328a0644b

Correct Result--> 098f6bcd4621d373cade4e832627b4f6
My Result --> 98f6bcd4621d373cade4e832627b4f6

Code:
Private Function GetPasswordHash(ByVal Password As String) As String
        Dim MD5Hasher As New System.Security.Cryptography.MD5CryptoServiceProvider
        Dim Encoder As New System.Text.ASCIIEncoding
        Dim FinalString As String
        FinalString = ToHexString(MD5Hasher.ComputeHash(Encoder.GetBytes(Password)))
        Return FinalString
    End Function

    Private Function ToHexString(ByVal ByteArray As Byte()) As String
        Dim i, j, k As Integer
        Dim thisstring As StringBuilder = New StringBuilder
        j = ByteArray.GetLowerBound(0)
        k = ByteArray.GetUpperBound(0)
        For i = j To k
            thisstring.Append(Hex(ByteArray(i)))
        Next
        Return thisstring.ToString
    End Function

I think the problem is that somewhere inside the ByteArray, it is dropping the leading 0s, as in changing:

09

to

9

And thereby screwing up the process... can anyone help? :)
 
try this:

Code:
    Private Function ToHexString(ByVal ByteArray As Byte()) As String
        Dim i, j, k As Integer
        Dim str As String
        Dim thisstring As System.Text.StringBuilder = New System.Text.StringBuilder()
        j = ByteArray.GetLowerBound(0)
        k = ByteArray.GetUpperBound(0)
        For i = j To k
            str = Convert.ToString(ByteArray(i), 16)
            If str.Length < 2 Then str = "0" + str
            thisstring.Append(str)
        Next
        Return thisstring.ToString
    End Function

hope this helps!

Andreas
 
Thanks m8, but I already found the solution myself :)

Code:
        Dim md5Hasher As New MD5CryptoServiceProvider

        Dim hashedDataBytes As Byte()
        Dim encoder As New UTF8Encoding

        hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(TextBox1.Text))

        Dim b As Byte
        For Each b In hashedDataBytes
            Label1.Text &= String.Format("{0:X2}", b)
        Next b

Does the trick nicely :)
 
Back
Top