Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vba Excel "automation error" from SHA256 and HMACSHA256 Functions

Tags:

excel

vba

Currently getting an Automation error in my code on the lines (note, this error only occurs on windows 10)

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

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

Here is the full function

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

From my testing and research I have found that this error on these lines has something to do with .netframework version 4.6. Installing version 3.5 of .netframework fixes this error and allows the code to run correctly. However this spreadsheet is to be given to clients, and I would rather have the function work without having to request the client install 3.5 (the spreadsheet needs to be all the client needs to use all of its functionality, ie they must not have to install anything (other than office), all must be contained within the excel document)

Does anyone know another way of doing this? I found a way to do a SHA256 using a class module, but this does not work HMACSHA256. I need a way to do both.

like image 761
Alex.M Avatar asked Oct 19 '22 02:10

Alex.M


2 Answers

So I fixed this myself in the end. I found another class module that does all the jobs previously done by the .net components.

I found the class module at http://www.vbforums.com/showthread.php?635398-VB6-HMAC-SHA-256-HMAC-SHA-1-Using-Crypto-API

And here is my updated Code:

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
like image 148
Alex.M Avatar answered Nov 15 '22 07:11

Alex.M


This issue can be solved by installing the .NET Framework 3.5, which can be found here: https://www.microsoft.com/en-ca/download/details.aspx?id=21

like image 38
clementgamache Avatar answered Nov 15 '22 07:11

clementgamache