Search code examples
excelvbasha256.net-4.8.net-framework-version

SHA 256 VBA for Excel without .netframework


I have an office laptop which doesn't allow installation of 3.5 .netframework hence cant use below function for hashing in VBA

System.Security.Cryptography.SHA256Managed

Was wondering is there an alternative code or procedure to use 256 hashing with standard 4.8 .net framework containers ?

Thanks

Tried using below code but not yielding result

Function StringToSHA256Hex(ByVal s As String) As String
Dim enc As Object
Dim bytes() As Byte
Dim pos As Long
Dim outstr As String

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

bytes = StrConv(s, vbFromUnicode)
bytes = enc.ComputeHash_2(bytes)

For pos = LBound(bytes) To UBound(bytes)
   outstr = outstr & LCase(Right("0" & Hex(bytes(pos)), 2))
Next pos

StringToSHA256Hex = outstr
Set enc = Nothing
End Function

Solution

  • The reason is that the library is obsolete. Also, you should be able to use VBA and the CNG (Next Generation Cryptography) API only.

    For example:

    ' Return a Base64 encoded hash of a string using the specified hash algorithm.
    ' By default, hash algorithm SHA256 is used.
    '
    ' Example:
    '   Text = "Get your filthy hands off my desert."
    '   Value = Hash(Text)
    '   Value -> "AIPgWDlQLv7bvLdg7Oa78dyRbC0tStuEXJRk0MMehOc="
    '
    ' Length of the generated Base64 encoded hash string:
    '
    '   Encoding    Length
    '   MD2         24
    '   MD4         24
    '   MD5         24
    '   SHA1        28
    '   SHA256      44      ' Default.
    '   SHA384      64
    '   SHA512      88
    '
    ' 2021-10-24. Gustav Brock, Cactus Data ApS, CPH.
    '
    Public Function Hash( _
        ByVal Text As String, _
        Optional ByVal BcryptHashAlgorithmId As BcHashAlgorithm = BcHashAlgorithm.bcSha256) _
        As String
        
        Dim HashBase64          As String
        
        If Text = "" Then
            ' No data. Nothing to do.
        Else
            HashBase64 = ByteBase64(HashData((Text), BcryptHashAlgorithmId))
        End If
        
        Hash = HashBase64
        
    End Function
    

    taken from my repository at GitHub: VBA.Cryptography.