4

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

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

MSDN 参考: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
4

2 回答 2

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
于 2012-07-10T09:36:35.630 回答
2

我无法让图书馆链接,所以我无法自己测试......

你的意思是也分配这样的结果吗?

result = instance.ComputeHash(data)

深入研究您提供的链接,我发现了这个例子:

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

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

这在我的脑海中似乎不正确,但同样,我无法确定测试,但他们已在声明()末尾添加。New你试过吗?

于 2012-07-09T14:11:43.810 回答