在VBA上计算SHA512(Excel 2003)

我试图计算VBA(Excel 2003)上的string的散列,但是当我调用ComputeHash ,它会引发一个Invalid argument/procedure call错误。

DLL参考:mscorlib v4.0,系统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 

你不能这样使用它,但你几乎在那里。 由于.ComputeHash是一个可重载的函数,而VBA无法处理这个问题,所以你需要明确你想调用的函数。 所以考虑下面的,使用UTF-8string编码为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 

我不能让图书馆链接,所以我不能testing这个自己…

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

 result = instance.ComputeHash(data) 

深入了解你提供的链接,我发现这个例子:

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

这在我的脑海中看起来并不正确,但是我再也无法确定,但是他们在New声明的末尾添加了() 。 你尝试过吗?