目前在我的代码中出现自动化错误(注意,此错误仅发生在 Windows 10 上)
Set oUTF = CreateObject("System.Text.UTF8Encoding")
Set oEnc = CreateObject("System.Security.Cryptography.SHA256Managed")
Run Code Online (Sandbox Code Playgroud)
这是完整的功能
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
Run Code Online (Sandbox Code Playgroud)
通过我的测试和研究,我发现这些行上的这个错误与 .netframework 4.6 版有关。安装 .netframework 的 3.5 版修复了这个错误并允许代码正确运行。但是,此电子表格将提供给客户,我宁愿让该功能工作而不必请求客户端安装 3.5(电子表格需要是客户端使用其所有功能所需的全部内容,即他们不必安装任何东西(office 除外),都必须包含在 excel 文档中)
有谁知道另一种方法吗?我找到了一种使用类模块执行 SHA256 的方法,但这不适用于 HMACSHA256。我需要一种方法来做到这两点。
所以我最后自己解决了这个问题。我发现另一个类模块可以完成以前由 .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
Run Code Online (Sandbox Code Playgroud)