在 VBA 上计算 SHA512 (Excel 2003)

2023-12-31

我正在尝试在 VBA (Excel 2003) 上计算字符串的哈希值,但是当我调用ComputeHash,它给了我一个Invalid argument/procedure call error.

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

MSDN 参考:http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512management.aspx 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

你还不能完全像那样使用它,但你已经差不多了。由于 .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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 VBA 上计算 SHA512 (Excel 2003) 的相关文章

随机推荐