在VBA上计算SHA512(Excel 2003) [英] Compute SHA512 on VBA (Excel 2003)

查看:235
本文介绍了在VBA上计算SHA512(Excel 2003)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

DLL References: 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

推荐答案

您不能完全那样使用​​它,但是您已经快到了.由于.ComputeHash是可重载的函数,而VBA无法处理此函数,因此需要明确说明要在哪个函数中调用.因此,请考虑以下内容,并使用UTF-8字符串将其编码为base64:

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:

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

这篇关于在VBA上计算SHA512(Excel 2003)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆