在VBA上计算SHA512(Excel 2003)

时间:2012-07-09 12:13:54

标签: excel vba hash excel-vba sha512

我正在尝试计算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

2 个答案:

答案 0 :(得分:4)

你不能那样使用它,但你几乎就在那里。由于.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

答案 1 :(得分: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。你试过了吗?