WoF_Angel
WoF_Angel

Reputation: 2581

Compute SHA512 on VBA (Excel 2003)

I'm trying to compute the hash of a string on VBA (Excel 2003), but when I call ComputeHash, it throws me an Invalid argument/procedure call error.

DLL References: mscorlib v4.0, System v4.0

MSDN reference: http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512managed.aspx

 Sub Main()
        Dim instance As New SHA512Managed
        Dim data() As Byte
        data = StringToByte("mymsg")
        Dim result() As Byte
        instance.ComputeHash(data) 'Throws runtime error'
        MsgBox (ByteToString(result))
    End Sub

    Function StringToByte(ByVal s)
        Dim b() As Byte           
        b = s  'Assign Unicode string to bytes.'
        StringToByte = b
    End Function

    Function ByteToString(ByVal dBytes)
        Dim strText As String
        strText = dBytes
        ByteToString = strText
    End Function

Upvotes: 4

Views: 9003

Answers (2)

SWa
SWa

Reputation: 4363

You can't quite use it like that, but you're almost there. Since .ComputeHash is an overloadable function, and VBA can't handle this you need to be explicit in which function you want to call. So consider the below, encoded to base64 using a UTF-8 string:

Sub test()
Dim text As Object
Dim SHA512 As Object

Set text = CreateObject("System.Text.UTF8Encoding")
Set SHA512 = CreateObject("System.Security.Cryptography.SHA512Managed")

Debug.Print ToBase64String(SHA512.ComputeHash_2((text.GetBytes_4("Hello World"))))

End Sub

Function ToBase64String(rabyt)

  'Ref: http://stackoverflow.com/questions/1118947/converting-binary-file-to-base64-string
  With CreateObject("MSXML2.DOMDocument")
    .LoadXML "<root />"
    .DocumentElement.DataType = "bin.base64"
    .DocumentElement.nodeTypedValue = rabyt
    ToBase64String = Replace(.DocumentElement.text, vbLf, "")
  End With
End Function

Upvotes: 5

Gaffi
Gaffi

Reputation: 4367

I can't get the library to link, so I can't test this myself...

Do you mean also to assign result like this?

result = instance.ComputeHash(data)

Looking deeper into that link you provided, I found this example:

Dim data(DATA_SIZE) As Byte
Dim result() As Byte

Dim shaM As New SHA512Managed()
result = shaM.ComputeHash(data)

This doesn't seem correct in my head, but again, I can't test for sure, but they've added () at the end of the New declaration. Have you tried that?

Upvotes: 2

Related Questions