在VBA上计算SHA512(Excel 2003)

WoF*_*gel 4 excel hash vba excel-vba sha512

我正在尝试在VBA(Excel 2003)上计算字符串的哈希,但是当我调用时ComputeHash,它将抛出Invalid argument/procedure call错误。

DLL参考:mscorlib v4.0,System v4.0

MSDN参考:http : //msdn.microsoft.com/zh-cn/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
Run Code Online (Sandbox Code Playgroud)

SWa*_*SWa 5

您不能完全那样使用​​它,但是您已经快到了。由于.ComputeHash是可重载的函数,而VBA无法处理此函数,因此需要明确指出要调用的函数。因此,请考虑以下内容,使用UTF-8字符串将其编码为base64:

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
Run Code Online (Sandbox Code Playgroud)