【问题标题】:Vba Excel "automation error" from SHA256 and HMACSHA256 Functions来自 SHA256 和 HMACSHA256 函数的 Vba Excel“自动化错误”
【发布时间】:2017-01-13 09:02:12
【问题描述】:

目前在我的代码中出现自动化错误(注意,此错误仅发生在 Windows 10 上)

Set oUTF = CreateObject("System.Text.UTF8Encoding")

Set oEnc = CreateObject("System.Security.Cryptography.SHA256Managed")

这是完整的功能

Function HMACSHA256(strToSign As String, strKey() As Byte)
Dim lngLoop As Long
Dim oUTF, oEnc
Dim HMAC() As Byte
Dim lastrow As Long

On Error GoTo err_handler

Set oUTF = CreateObject("System.Text.UTF8Encoding")
Set oEnc = CreateObject("System.Security.Cryptography.HMACSHA256")
oEnc.key = strKey
HMAC = oEnc.ComputeHash_2(oUTF.GetBytes_4(strToSign)) 

HMACSHA256 = HMAC

Exit Function

err_handler:
    Worksheets("Log Sheet").Cells(lastrow, 4) = "Fail"
    Worksheets("Log Sheet").Cells(lastrow, 5) = Err.Description
    MsgBox Err.Description, vbCritical

End Function

根据我的测试和研究,我发现这些行中的此错误与 .netframework 4.6 版有关。安装 .netframework 3.5 版可修复此错误并允许代码正确运行。但是,此电子表格将提供给客户,我宁愿让功能工作而不必请求客户端安装 3.5(电子表格需要是客户端使用其所有功能所需的全部,即他们必须不必安装任何东西(除了办公室),都必须包含在 excel 文档中)

有人知道另一种方法吗?我找到了一种使用类模块执行 SHA256 的方法,但这不适用于 HMACSHA256。我需要一种方法来做到这两点。

【问题讨论】:

  • 这些System.Text.UTF8EncodingSystem.Security.Cryptography.SHA256Managed 应该在参考列表Goto--> tools--.reference 中。
  • 这是 Microsoft .NET Framework 类。计算机上是否安装了 Microsoft .NET Framework?
  • 是的,.netframework 4.6 是默认从 windows 10 上的 windows 更新安装的,但是该代码仅适用于 3.5,默认情况下不安装
  • 如果您已经可以访问实现 SHA256 的类模块,那么用 HMAC 包装它应该不会复杂。查看spec summary 和一些sample pseudocode 了解它是如何完成的。可能比让 .NET 正常运行更容易。

标签: vba excel


【解决方案1】:

所以我最终自己解决了这个问题。我发现了另一个类模块,它完成了以前由 .net 组件完成的所有工作。

我在以下位置找到了类模块 http://www.vbforums.com/showthread.php?635398-VB6-HMAC-SHA-256-HMAC-SHA-1-Using-Crypto-API

这是我更新后的代码:

Function HMACSHA256A(strToSign As String, strKey() As Byte)

    Dim lngLoop As Long
    Dim oUTF, oEnc
    Dim HMAC() As Byte
    Dim lastrow As Long
    Dim byteString() As Byte

    On Error GoTo err_handler
    lastrow = FindLastRow
    Set Test = New HS256
    Test.InitHmac strKey
    byteString = Test.ToUTF8(strToSign)
    HMACSHA256A = Test.HMACSHA256(byteString)
    Worksheets("Log Sheet").Cells(lastrow, 4) = "Pass"
    Exit Function

err_handler:
    Worksheets("Log Sheet").Cells(lastrow, 4) = "Fail"
    Worksheets("Log Sheet").Cells(lastrow, 5) = Err.Description
    MsgBox Err.Description, vbCritical

End Function

【讨论】:

  • 请在答案中包含HS256 类模块代码。
【解决方案2】:

这个问题可以通过安装 .NET Framework 3.5 来解决,可以在这里找到:https://www.microsoft.com/en-ca/download/details.aspx?id=21

【讨论】:

  • "但是这个电子表格是给客户的,我宁愿让功能工作而不必请求客户安装 3.5"
猜你喜欢
  • 1970-01-01
  • 2014-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 2022-07-22
  • 2017-04-06
相关资源
最近更新 更多