Compute SHA512 on VBA (Excel 2003)

柔情痞子 提交于 2019-12-10 17:37:09

问题


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

回答1:


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



回答2:


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?



来源:https://stackoverflow.com/questions/11394811/compute-sha512-on-vba-excel-2003

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!