Posts Tagged vba

MD5 HMAC with VBA or VB. Visual Basic brought me back

Hi blog. Long time no see.

I searched some time for hmac md5 creation in VBA or VB, to be able to send hmac signed data with Excel,Access or Word. Eventually i found some code in the net and put them together, and now it works.
So if you want to connect to a REST webservice, that uses hmac with md5, from any Microsoft Office Program, this little functions may be useful to you.
For creating a signature the code first uses the cryptography functions of the system. The return value is a byte array, so if you want to see the md5 you have to transform that byte array in to readable md5. That is what the little helper function ByteArrayToHex() is for.

' Reference:
Public Function hash_HMACMD5(ByVal sTextToHash As String, ByVal sSharedSecretKey As String)

    Dim asc As Object, enc As Object
    Dim TextToHash() As Byte
    Dim SharedSecretKey() As Byte
    Set asc = CreateObject("System.Text.UTF8Encoding")
    Set enc = CreateObject("System.Security.Cryptography.HMACMD5")

    TextToHash = asc.Getbytes_4(sTextToHash)
    SharedSecretKey = asc.Getbytes_4(sSharedSecretKey)
    enc.Key = SharedSecretKey

    Dim bytes() As Byte
    bytes = enc.ComputeHash_2((TextToHash))

    hash_HMACMD5 = ByteArrayToHex(bytes)
    Set asc = Nothing
    Set enc = Nothing

End Function

' Referenz:
Private Function ByteArrayToHex(ByRef ByteArray() As Byte) As String
    Dim l As Long, strRet, Val As String
    For l = LBound(ByteArray) To UBound(ByteArray)
        Val = Hex$(ByteArray(l))
        If Len(Val) <> 2 Then
             Val = "0" & Val
        End If
        strRet = strRet & Val
    Next l
    ByteArrayToHex = LCase(strRet)
End Function

Use it like this:

hmac = hash_HMACMD5(“My Text i want to hash today”, “MY_TOTAL_SECRET_SECRET”)


, ,

Leave a comment

%d bloggers like this: