Search code examples
ms-access-2016sha512

Hash function value changing from day to day with same input


I have a simple hash function I copied from https://en.wikibooks.org/wiki/Visual_Basic_for_Applications/String_Hashing_in_VBA. It hashes just fine. I rehashed the text and it matched the saved hash. I tried it again on a different day and the same text hashes to a different value.

Public Function SHA512(ByVal sIn As String, Optional bB64 As Boolean = 0) As String
    'Set a reference to mscorlib 4.0 64-bit

    'Test with empty string input:
    '128 Hex:   cf83e1357eefb8bd...etc
    '88 Base-64:   z4PhNX7vuL3xVChQ...etc

    Dim oT As Object, oSHA512 As Object
    Dim TextToHash() As Byte, bytes() As Byte

    Set oT = CreateObject("System.Text.UTF8Encoding")
    Set oSHA512 = CreateObject("System.Security.Cryptography.SHA512Managed")

    TextToHash = oT.Getbytes_4(sIn)
    bytes = oSHA512.ComputeHash_2((TextToHash))

    If bB64 = True Then
       SHA512 = ConvToBase64String(bytes)
    Else
       SHA512 = ConvToHexString(bytes)
    End If

    Set oT = Nothing
    Set oSHA512 = Nothing

End Function

Private Function ConvToHexString(vIn As Variant) As Variant

    Dim oD As Object

    Set oD = CreateObject("MSXML2.DOMDocument")

      With oD
        .LoadXML "<root />"
        .DocumentElement.DataType = "bin.Hex"
        .DocumentElement.nodeTypedValue = vIn
      End With
    ConvToHexString = Replace(oD.DocumentElement.Text, vbLf, "")

    Set oD = Nothing

End Function

Solution

  • Solved my problem. The hash was hashing some random cache value. Rewrote the passing of the value to the hash function.