在 VBA (Excel 2003) 上计算 SHA512
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11394811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compute SHA512 on VBA (Excel 2003)
提问by WoF_Angel
I'm trying to compute the hash of a string on VBA (Excel 2003), but when I call ComputeHash
, it throws me an Invalid argument/procedure call
error.
我正在尝试在 VBA (Excel 2003) 上计算字符串的哈希值,但是当我调用 时ComputeHash
,它会抛出一个Invalid argument/procedure call
错误。
DLL References: mscorlib v4.0, System v4.0
DLL 参考:mscorlib v4.0、System v4.0
MSDN reference: http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512managed.aspx
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
回答by SWa
You can't quite use it like that, but you're almost there. Since .ComputeHash is an overloadable function, and VBA can't handle this you need to be explicit in which function you want to call. So consider the below, encoded to base64 using a UTF-8 string:
你不能像那样使用它,但你几乎就在那里。由于 .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
回答by Gaffi
I can't get the library to link, so I can't test this myself...
我无法链接库,所以我无法自己测试...
Do you mean also to assign result like this?
你的意思也是这样分配结果吗?
result = instance.ComputeHash(data)
Looking deeper into that link you provided, I found this example:
深入研究您提供的链接,我发现了这个例子:
Dim data(DATA_SIZE) As Byte
Dim result() As Byte
Dim shaM As New SHA512Managed()
result = shaM.ComputeHash(data)
This doesn't seem correct in my head, but again, I can't test for sure, but they've added ()
at the end of the New
declaration. Have you tried that?
这在我看来似乎不正确,但同样,我无法确定测试,但它们已添加()
到New
声明的末尾。你试过吗?