Vba Excel“automation error”来自SHA256和HMACSHA256函数

5

我在我的代码中的这些行出现了自动化错误(请注意,此错误仅在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

从我的测试和研究中,我发现这些行上的错误与.NET Framework版本4.6有关。安装.NET Framework 3.5版本可以修复此错误并允许代码正确运行。然而,这个电子表格将被提供给客户使用,我宁愿使函数能够在不要求客户安装3.5的情况下正常工作(电子表格需要是客户使用其所有功能所需的全部内容,即他们不必安装任何东西(除了办公软件)。所有内容必须包含在Excel文档中)。
有人知道另一种方法吗?我找到了一种使用类模块进行SHA256的方法,但这不适用于HMACSHA256。我需要一种同时做到这两个的方法。

1
这些 System.Text.UTF8EncodingSystem.Security.Cryptography.SHA256Managed 应该在参考列表中。前往 --> 工具 --> 引用。 - Techie
这些是Microsoft .NET Framework类。计算机上安装了Microsoft .NET Framework吗? - Axel Richter
是的,在Windows 10上,.NET Framework 4.6默认通过Windows更新安装,但是代码只能在3.5上运行,而3.5并未默认安装。 - Alex.M
如果你已经有访问实现SHA256的类模块,那么使用HMAC包装它应该不会太复杂。查看规范摘要和一些样例伪代码,以了解如何完成此操作的思路。这可能比让.NET正常运行更容易。 - Mikegrann
2个回答

2
最终我自己解决了这个问题。我找到了另一个类模块,它可以完成以前由.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

1
请将 HS256 类模块代码包含在答案中。 - omegastripes

1

4
然而,这个电子表格将要交给客户使用,我宁愿让这个函数能够正常运行,而不需要要求客户安装3.5版本。 - SierraOscar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接