Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello,

Been pulling my hair out trying figure out how to calculate the MD5 for a string of HEX characters. My code considers the input as text string, not hex string. How do I get VB to consider the string as HEX?

Here is the HEX string I want to calculate MD5 for: "464645363730433739316C2C011002FFE670C791F149CD1ABFBF8CE63278076A0A29FCE6DD55B343DC0891C5A7F0538CA42638A9CA6ABCA9A2DC117CEE331D2830E8403BEECA2B6C4D3E1B8B09E9CD7AA9517F4CBBE2CDB8DF630127DA922D072E95AEB32EF89B2F23BE29B0B6278AE4A2A44B252D902FEC3B65828ECAA6C224DD99E18021EF8C42A948F828D67E38A6B52CF7A4E49DA7610ED0C93941F27850D97F56C241A4562B5CCA2DEA8D392924976E5A95038B2754D98A86D88B807C243C9617C03232BFCAF4B107DEDC0CA99EFCCF7A2A78E5FF79E40B4F70BD3D07D9FFFCE7210736A43621724BE4F853659F24C0DC53CCC5D606AB077D212B5F1288B20F2311077AD18EE2027981497AE59CB7B1C5E7E6156FC4E48CF1CA5624BB2113FDB409B7DB9C78175F479954DD8B7A6D18F3937B1C254BC107FABD8B71FC532E17D88982DBC55E6D5A3459D849F2B2C13D6629B8668BE4F02D00D1B36CD2EFE6268B02320B3986CCD4B74A0404DC7BB765DEC58364C305F89FC9D7D21412EF8473FAEC79FDD0DAD1DB1DED6FB163E58FFA656894D2FF0EE4F4E4640010688E9C657C0EE437ACBD243CBDC84B01D1AE5302D2C184D2DE326DEDCFEE8C53120107C40D560A6871137BEEA662CF4E88C699F78807620CB4A8FE4A6F952C571FEF4CD3FA37AD75D1404E66EB5EA47A73AB76CAF1B7AD2EC9DFA8E4EFD31D2573C932F6DE130B1225711BE16F4D2EBF38E7A6F5EA2B8112F0A0326FB089A387AF9F62A0BBD653D6827114970D883C250AC69A80207F127235B32BD744B11AF6B9A13DC143A06B16A54267F5A70430E792BD5929E2BF"

MD5 for string as text = "A44D49B12BD10CDAF08A034638F8141B"
MD5 for string as hex = "E514481E8E3344F37A3F1E2BBFC84EEF"

Here is the code I have so far:


VB
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        hashblob = "464645363730433739316C2C011002FFE670C791F149CD1ABFBF8CE63278076A0A29FCE6DD55B343DC0891C5A7F0538CA42638A9CA6ABCA9A2DC117CEE331D2830E8403BEECA2B6C4D3E1B8B09E9CD7AA9517F4CBBE2CDB8DF630127DA922D072E95AEB32EF89B2F23BE29B0B6278AE4A2A44B252D902FEC3B65828ECAA6C224DD99E18021EF8C42A948F828D67E38A6B52CF7A4E49DA7610ED0C93941F27850D97F56C241A4562B5CCA2DEA8D392924976E5A95038B2754D98A86D88B807C243C9617C03232BFCAF4B107DEDC0CA99EFCCF7A2A78E5FF79E40B4F70BD3D07D9FFFCE7210736A43621724BE4F853659F24C0DC53CCC5D606AB077D212B5F1288B20F2311077AD18EE2027981497AE59CB7B1C5E7E6156FC4E48CF1CA5624BB2113FDB409B7DB9C78175F479954DD8B7A6D18F3937B1C254BC107FABD8B71FC532E17D88982DBC55E6D5A3459D849F2B2C13D6629B8668BE4F02D00D1B36CD2EFE6268B02320B3986CCD4B74A0404DC7BB765DEC58364C305F89FC9D7D21412EF8473FAEC79FDD0DAD1DB1DED6FB163E58FFA656894D2FF0EE4F4E4640010688E9C657C0EE437ACBD243CBDC84B01D1AE5302D2C184D2DE326DEDCFEE8C53120107C40D560A6871137BEEA662CF4E88C699F78807620CB4A8FE4A6F952C571FEF4CD3FA37AD75D1404E66EB5EA47A73AB76CAF1B7AD2EC9DFA8E4EFD31D2573C932F6DE130B1225711BE16F4D2EBF38E7A6F5EA2B8112F0A0326FB089A387AF9F62A0BBD653D6827114970D883C250AC69A80207F127235B32BD744B11AF6B9A13DC143A06B16A54267F5A70430E792BD5929E2BF"

        Using md5Hash As MD5 = MD5.Create()

            Dim hash As String = GetMd5Hash(md5Hash, hashblob2)
            Debug.Print(hash)
        End Using

    End Sub

    Shared Function GetMd5Hash(ByVal md5Hash As MD5, ByVal input As String) As String

        'Convert the input string to a byte array and compute the hash.
        Dim data = md5Hash.ComputeHash(Encoding.Default.GetBytes(input))

        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As New StringBuilder()

       ' Loop through each byte of the hashed data
        '' and format each one as a hexadecimal string.
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("X2"))
        Next i

       ' Return the hexadecimal string.
        Return sBuilder.ToString()

    End Function 'GetMd5Hash


Can anyone please tell me how to change my code to treat string as hex instead of text?

Appreciate any help or guidance!
Posted
Comments
Sergey Alexandrovich Kryukov 17-Mar-14 10:07am    
Your problem is that you are not formulating what do you want to achieve, so I'm not sure you really understand it by yourself. You just say "MD5 for string as hex = ...". What do you mean by that? Get numeric data represented by the string and hash this numeric data instead? You should understand, there is no such thing as "hex string" per se, you should explain what interpretation of that string is implied.
—SA
steveharan 17-Mar-14 10:16am    
Sorry I did not articulate correctly. Yes I want to calc MD5 for a string containing many hex charecters. Do I need to create another string builder to convert the hex string to a byte array or something first?

Sergey Alexandrovich Kryukov 17-Mar-14 10:20am    
There is no such thing as "hex character". The problem can be ambiguous. What is that data in the string? Sequence of bytes? Something else? By the way, how are you going to use this hash? In certain sense, it can be not important what form of data to you use to get hash. You would get different results, so what? It is important to know what would you use this hash for.
—SA
steveharan 17-Mar-14 10:48am    
We have some equipment that returns the following string to the test station PC. We use the MD5 hex result to verify the data.
"464645363730433739316C2C011002FFE670C791F149CD1ABFBF8CE63278076A0A29FCE6DD55B343DC0891C5A7F0538CA42638A9CA6ABCA9A2DC117CEE331D2830E8403BEECA2B6C4D3E1B8B09E9CD7AA9517F4CBBE2CDB8DF630127DA922D072E95AEB32EF89B2F23BE29B0B6278AE4A2A44B252D902FEC3B65828ECAA6C224DD99E18021EF8C42A948F828D67E38A6B52CF7A4E49DA7610ED0C93941F27850D97F56C241A4562B5CCA2DEA8D392924976E5A95038B2754D98A86D88B807C243C9617C03232BFCAF4B107DEDC0CA99EFCCF7A2A78E5FF79E40B4F70BD3D07D9FFFCE7210736A43621724BE4F853659F24C0DC53CCC5D606AB077D212B5F1288B20F2311077AD18EE2027981497AE59CB7B1C5E7E6156FC4E48CF1CA5624BB2113FDB409B7DB9C78175F479954DD8B7A6D18F3937B1C254BC107FABD8B71FC532E17D88982DBC55E6D5A3459D849F2B2C13D6629B8668BE4F02D00D1B36CD2EFE6268B02320B3986CCD4B74A0404DC7BB765DEC58364C305F89FC9D7D21412EF8473FAEC79FDD0DAD1DB1DED6FB163E58FFA656894D2FF0EE4F4E4640010688E9C657C0EE437ACBD243CBDC84B01D1AE5302D2C184D2DE326DEDCFEE8C53120107C40D560A6871137BEEA662CF4E88C699F78807620CB4A8FE4A6F952C571FEF4CD3FA37AD75D1404E66EB5EA47A73AB76CAF1B7AD2EC9DFA8E4EFD31D2573C932F6DE130B1225711BE16F4D2EBF38E7A6F5EA2B8112F0A0326FB089A387AF9F62A0BBD653D6827114970D883C250AC69A80207F127235B32BD744B11AF6B9A13DC143A06B16A54267F5A70430E792BD5929E2BF"
I need to calculate the MD5 for the string above, but my code process the data as string of text characters instead of a string of hex characters.
MD5 for string as text (current code returns this) = "A44D49B12BD10CDAF08A034638F8141B"
MD5 for string as hex (need code to return this) = "E514481E8E3344F37A3F1E2BBFC84EEF"
steveharan 17-Mar-14 11:00am    
If I go to "http://www.fileformat.info/tool/hash.htm" and paste the string in the "string hash" field I get "A44D49B12BD10CDAF08A034638F8141B". If paste the string in the "binary hash" field I get "E514481E8E3344F37A3F1E2BBFC84EEF". How do I get my code to get same result as binary string?

There is no "tidy" way to do this: converting a hex string to a byte array isn't covered by the .NET framwork!

But it's not too complex:
C#
private static byte[] ConvertHex(string hex)
    {
    if (hex.Length % 2 == 1) throw new ArgumentException("The hexadecimal data cannot have an odd number of digits");

    int bytes = hex.Length / 2;
    byte[] result = new byte[bytes];
    int inputIndex = 0;
    for (int i = 0; i < bytes; i++)
        {
        result[i] = (byte)((GetHexNibble(hex[inputIndex++]) << 4) + (GetHexNibble(hex[inputIndex++])));
        }
    return result;
    }

private static int GetHexNibble(char hex)
    {
    if (hex <= '9') return hex - '0';
    return (hex - 'A') + 10;
    }




"I am just a tech with little programming skills, do not know C# at all... Can you send code in VB?


VB
Private Shared Function ConvertHex(hex As String) As Byte()
    If hex.Length Mod 2 = 1 Then
        Throw New ArgumentException("The hexadecimal data cannot have an odd number of digits")
    End If

    Dim bytes As Integer = hex.Length \ 2
    Dim result As Byte() = New Byte(bytes - 1) {}
    Dim inputIndex As Integer = 0
    For i As Integer = 0 To bytes - 1
        Dim hi As Integer = GetHexNibble(hex(inputIndex))
        inputIndex += 1
        Dim lo As Integer = GetHexNibble(hex(inputIndex))
        inputIndex += 1
        result(i) = CByte(hi * 4 + lo)
    Next
    Return result
End Function

Private Shared Function GetHexNibble(hex As Char) As Integer
    If hex <= "9"C Then
        Return hex - "0"C
    End If
    Return (hex - "A"C) + 10
End Function
 
Share this answer
 
v2
Comments
steveharan 17-Mar-14 12:22pm    
I converted these two functions into VB, but I am getting a "Arithmetic operation resulted in an overflow for "result(i) = CByte((GetHexNibble(hex(System.Math.Max(System.Threading.Interlocked.Increment(inputIndex), inputIndex - 1))) << 4) + (GetHexNibble(hex(System.Math.Max(System.Threading.Interlocked.Increment(inputIndex), inputIndex - 1)))))"

Code:

Private Shared Function ConvertHex(ByVal hex As String) As Byte()
If hex.Length Mod 2 = 1 Then
Throw New ArgumentException("The hexadecimal data cannot have an odd number of digits")
End If

Dim bytes As Integer = hex.Length / 2
Dim result As Byte() = New Byte(bytes - 1) {}
Dim inputIndex As Integer = 0
For i As Integer = 0 To bytes - 1
result(i) = CByte((GetHexNibble(hex(System.Math.Max(System.Threading.Interlocked.Increment(inputIndex), inputIndex - 1))) << 4) + (GetHexNibble(hex(System.Math.Max(System.Threading.Interlocked.Increment(inputIndex), inputIndex - 1)))))
Next
Return result
End Function

Private Shared Function GetHexNibble(ByVal hex As Char) As Integer
If hex <= "9"c Then
Return hex & "0"c
End If
Return (hex & "A"c) + 10
End Function
OriginalGriff 17-Mar-14 13:25pm    
I think you need to revisit C#: << and >> are shift operators. Try:
(GetHexNibble(hex[inputIndex++]) * 16)
instead and convert that.
steveharan 17-Mar-14 14:08pm    
I am just a tech with little programming skills, do not know C# at all... Can you send code in VB?
OriginalGriff 17-Mar-14 15:15pm    
Answer updated - silly language, VB! :laugh:
steveharan 17-Mar-14 15:29pm    
Thank you soo much!

VB still has [prblem with the "-" charectars in the GetHexNibble function.

Private Shared Function GetHexNibble(hex As Char) As Integer
If hex <= "9"C Then
Return hex - "0"C
End If
Return (hex - "A"C) + 10
End Function

Tried to change as follows but get conversion error. "Conversion from string "CA" to type 'Double' is not valid."

Private Shared Function GetHexNibble(ByVal hex As Char) As Integer
If hex <= "9"c Then
Return hex & "0"c
End If
Return (hex & "A"c) + 10
End Function

Can you help once more?
Just in case some other poor sap needs help doing this in VB, I figured out the solution with the help of a good friend and positive feedback from OriginalGriff!

I must admit the initial ARROGANT responses I received were extremely discouraging and unnecessary...

VB CODE:

Public Function HexDecode(ByVal s As String) As Byte()
Return HexDecode(s, 0)
End Function

Public Function HexDecode(ByVal s As String, ByVal paddingBytes As Integer) As Byte()
If s Is Nothing Then
Throw New ArgumentNullException("s")
End If

If s.IndexOf(":"c) > -1 Then
s = s.Replace(":", "")
End If

If (s.Length Mod 2) <> 0 Then
Throw New FormatException("parameter 's' must have an even number of hex characters")
End If

Dim result As Byte() = New Byte(s.Length \ 2 + (paddingBytes - 1)) {}
For i As Integer = 0 To result.Length - paddingBytes - 1
result(i) = Byte.Parse(s.Substring(i * 2, 2), NumberStyles.AllowHexSpecifier)
Next
Return result
End Function

Thanks to everyone who pointed me in the right direction!

Cheers
 
Share this answer
 
Hex code to byte array
--------------------------------------
C#
public static byte[] DecodeHex(string hextext)
{
   String[] arr = hextext.Split('-');
   byte[] array = new byte[arr.Length];
   for (int i = 0; i < arr.Length; i++)
         array[i] = Convert.ToByte(arr[i], 16);
   return array;
}

It guide you.
MD5 sample code for encrypt
-------------------------------------------
public static string Encrypt(string toEncrypt, bool useHashing, string imkey)
{
    byte[] keyArray;
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

    string key = imkey;
    if (useHashing)
    {
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        hashmd5.Clear();
    }
    else
        keyArray = UTF8Encoding.UTF8.GetBytes(key);

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    tdes.Key = keyArray;
    tdes.Mode = CipherMode.ECB;
    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateEncryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
    tdes.Clear();
    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
 
Share this answer
 
Comments
steveharan 17-Mar-14 14:30pm    
So I tried your code Soham and I get a overflow error "Value was either too large or too small for a UInt32." in the decodehex function.

Imports System.Security.Cryptography
Imports System.IO
Imports System.Text

Public Class Form1
Dim blob

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

blob = DecodeHex("464645363730433739316C2C011002FFE670C791F149CD1ABFBF8CE63278076A0A29FCE6DD55B343DC0891C5A7F0538CA42638A9CA6ABCA9A2DC117CEE331D2830E8403BEECA2B6C4D3E1B8B09E9CD7AA9517F4CBBE2CDB8DF630127DA922D072E95AEB32EF89B2F23BE29B0B6278AE4A2A44B252D902FEC3B65828ECAA6C224DD99E18021EF8C42A948F828D67E38A6B52CF7A4E49DA7610ED0C93941F27850D97F56C241A4562B5CCA2DEA8D392924976E5A95038B2754D98A86D88B807C243C9617C03232BFCAF4B107DEDC0CA99EFCCF7A2A78E5FF79E40B4F70BD3D07D9FFFCE7210736A43621724BE4F853659F24C0DC53CCC5D606AB077D212B5F1288B20F2311077AD18EE2027981497AE59CB7B1C5E7E6156FC4E48CF1CA5624BB2113FDB409B7DB9C78175F479954DD8B7A6D18F3937B1C254BC107FABD8B71FC532E17D88982DBC55E6D5A3459D849F2B2C13D6629B8668BE4F02D00D1B36CD2EFE6268B02320B3986CCD4B74A0404DC7BB765DEC58364C305F89FC9D7D21412EF8473FAEC79FDD0DAD1DB1DED6FB163E58FFA656894D2FF0EE4F4E4640010688E9C657C0EE437ACBD243CBDC84B01D1AE5302D2C184D2DE326DEDCFEE8C53120107C40D560A6871137BEEA662CF4E88C699F78807620CB4A8FE4A6F952C571FEF4CD3FA37AD75D1404E66EB5EA47A73AB76CAF1B7AD2EC9DFA8E4EFD31D2573C932F6DE130B1225711BE16F4D2EBF38E7A6F5EA2B8112F0A0326FB089A387AF9F62A0BBD653D6827114970D883C250AC69A80207F127235B32BD744B11AF6B9A13DC143A06B16A54267F5A70430E792BD5929E2BF")

End Sub


Public Shared Function DecodeHex(ByVal hextext As String) As Byte()
Dim arr As [String]() = hextext.Split("-"c)
Dim array As Byte() = New Byte(arr.Length - 1) {}
For i As Integer = 0 To arr.Length - 1
array(i) = Convert.ToByte(arr(i), 16)
Next
Return array
End Function
Public Shared Function Encrypt(ByVal toEncrypt As String, ByVal useHashing As Boolean, ByVal imkey As String) As String
Dim keyArray As Byte()
Dim toEncryptArray As Byte() = UTF8Encoding.UTF8.GetBytes(toEncrypt)

Dim key As String = imkey
If useHashing Then
Dim hashmd5 As New MD5CryptoServiceProvider()
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key))
hashmd5.Clear()
Else
keyArray = UTF8Encoding.UTF8.GetBytes(key)
End If

Dim tdes As New TripleDESCryptoServiceProvider()
tdes.Key = keyArray
tdes.Mode = CipherMode.ECB
tdes.Padding = PaddingMode.PKCS7

Dim cTransform As ICryptoTransform = tdes.CreateEncryptor()
Dim resultArray As Byte() = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)
tdes.Clear()
Return Convert.ToBase64String(resultArray, 0, resultArray.Length)
End Function

End Class
SOHAM_GANDHI 17-Mar-14 14:45pm    
Pass string as 46-46-45-36 as on..
46 is get convert to byte.


Error because.
it convert to byte as single number like 4 ,6 ,4, 6 , . . .

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900