Excel VBA Base64 HMAC SHA256 and SHA1 Encryption

VBA Base64 HMAC SHA256 and SHA1

To use this code, you need do this:
Inside the VBE, Go to Tools -> References, then Select Microsoft XML, v6.0 (or whatever your latest is. This will give you access to the XML Object Library.)

Public Function Base64_HMACSHA256(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.HMACSHA256")

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

    Dim bytes() As Byte
    bytes = enc.ComputeHash_2((TextToHash))
    Base64_HMACSHA256 = EncodeBase64(bytes)
    Set asc = Nothing
    Set enc = Nothing
End Function

Public Function Base64_HMACSHA1(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.HMACSHA1")

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

    Dim bytes() As Byte
    bytes = enc.ComputeHash_2((TextToHash))
    Base64_HMACSHA1 = EncodeBase64(bytes)
    Set asc = Nothing
    Set enc = Nothing

End Function

Private Function EncodeBase64(ByRef arrData() As Byte) As String

    'Inside the VBE, Go to Tools -> References, then Select Microsoft XML, v6.0
    '(or whatever your latest is. This will give you access to the XML Object Library.)

    Dim objXML As MSXML2.DOMDocument
    Dim objNode As MSXML2.IXMLDOMElement

    Set objXML = New MSXML2.DOMDocument

    ' byte array to base64
    Set objNode = objXML.createElement("b64")
    objNode.DataType = "bin.base64"
    objNode.nodeTypedValue = arrData
    EncodeBase64 = objNode.Text

    Set objNode = Nothing
    Set objXML = Nothing

End Function

Test

Base64 HMAC SHA256
debug.Print Base64_HMACSHA256("abc","1234567890")
hgVRhIBbSkZqe+OY/0pxWfkFXqfu8zn8lNzsbxZYmLo=

Base64 HMAC SHA1
debug.Print Base64_HMACSHA1("abc","1234567890")
2uVIIsDa9sEVyXsK1ix7y+nV5vw=

Check result here: Online HMAC Generator

Base64 HMAC SHA256 in different languages

If you need examples of creating base64 hashes using HMAC SHA256 in different languages (Javascript, PHP, Java, Groovy, C#, Objective C, Go, Ruby, Python, Perl, Dart, Swift, Rust, Powershell, Shell), read this post.

Comments

  1. Omar says

    Thank you very much! This is very useful. Using VBA, Do you know how can I decrypt the encryption if I know the SharedSecretKey?

Leave a Reply

Your email address will not be published. Required fields are marked *