0

我是编程和使用 Access 2010 VBA 的新手。我需要将一组规则应用于 xml 文件,以便我可以访问 API。我研究了不同的方法,但由于我的知识有限,每一种都被卡住了。如果有人能指出我正确的道路/提供一些建议,那就太好了。

规则:

  1. 将 xml 文件规范化为 W3C C14N 规范。
  2. SHA1 将 xml 散列为二进制以进行进一步编码
  3. Base64 和 Base32 对 SHA1 哈希进行编码

我的第一个问题是我找不到在 VBA 中 c14n xml 的任何方法。所以我跳过了这一步,因为我可以确保 xml 是预先规范化的。尽管理想情况下这将作为编码过程的一部分来完成,以防有人更改了先例 xml。

然后我开始查看 SHA1 哈希并找到了这个示例代码:

http://vb.wikia.com/wiki/SHA-1.bas

这里的问题是输出哈希是十六进制的,我认为我需要在转换为 base64 之前将其转换为字节数组。我找不到任何示例代码来执行此操作。

然后我遇到了这篇文章: Base64 HMAC SHA1 String in VBA

这是为 HMACSHA1 调用 .net cyptography 库,但有一个用于 SHA1 的库:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1.aspx

这里的问题是我不知道如何调用 .net 库的工作。我需要在办公室的 10 台不同的 windows 机器上运行这个软件,所以我需要了解它。

最后我找到了我需要在 vb.net 中编写的确切函数:

http://blog.kuffs.co.uk/2009/07/calculating-irmark-for-hmrc-gateway.html

同样,我对.net 没有经验,并且不确定如何将其构建到可访问的库中。

4

1 回答 1

2

Here you go:

Public Function SHA1Base64(ByVal sTextToHash As String)

    Dim asc As Object, enc As Object
    Dim TextToHash() As Byte
    Set asc = CreateObject("System.Text.UTF8Encoding")
    Set enc = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider")
    TextToHash = asc.Getbytes_4(sTextToHash)
    Dim bytes() As Byte
    bytes = enc.ComputeHash_2((TextToHash))
    SHA1Base64 = EncodeBase64(bytes)
    Set asc = Nothing
    Set enc = Nothing

End Function

Private Function EncodeBase64(ByRef arrData() As Byte) As String

    Dim objXML As MSXML2.DOMDocument
    Dim objNode As MSXML2.IXMLDOMElement

    Set objXML = New MSXML2.DOMDocument

    ' byte array to base64
    Set objNode = objXML.createElement("b64")
    objNode.DataType = "bin.base64"
    objNode.nodeTypedValue = arrData
    EncodeBase64 = objNode.Text

    Set objNode = Nothing
    Set objXML = Nothing

End Function

Be aware that not nearly every .NET Framework library is available to be used in VBA (without wrapping them in COM callable wrapper dll's anyway). It just so happens that the functions you need can be called directly from VBA. And yes, it's true that there's really not much documentation on this that I'm aware of and it's anything but intuitive. GetBytes_4 and ComputerHash_2 are actually "overloaded" functions in .NET, something that doesn't exist in VBA. It's basically where you declare the same function multiple times, but each time it takes different quantity and/or different types of arguments.

You may want to compare the output of these functions to some known good output from somewhere else. I say that only because I know this code is returning something but I don't know if it's what you're looking for.

于 2013-07-25T02:16:18.060 回答