Wednesday, January 1, 2025

SHA256 Hashing Function

I know this is not a new topic, but I just thought I would post it here for my own future reference.

I have used other SHA256 hashing functions before, but they were long and complicated with multiple loops.

I discovered that the same thing can be accomplished by taking advantage of some built-in .Net Framework methods.

The below function should work in Access VBA without any need for additional or external references.

Please let me know if you run into any issues or if you have any suggestions for improvements.

Happy New Year!

Function dbgSHA256(PlainText As String) As String
'thedbguy@gmail.com
'1/1/2025

Dim encoder As Object
Dim hasher As Object
Dim textToHash() As Byte
Dim hash() As Byte
Dim cypher() As String
Dim x As Long

' Create objects for encoding and hashing
Set encoder = CreateObject("System.Text.UTF8Encoding")
Set hasher = CreateObject("System.Security.Cryptography.SHA256Managed")

' Convert the input string to bytes
textToHash = encoder.GetBytes_4(PlainText)

' Compute the hash
hash = hasher.ComputeHash_2(textToHash)

' Convert the hash to a hexadecimal string
ReDim cypher(UBound(hash))
For x = 0 To UBound(hash)
    cypher(x) = Hex$(hash(x))
Next

' Return the result
dbgSHA256 = Join(cypher, "")

' Clean up objects
Set hasher = Nothing
Set encoder = Nothing

End Function