Attribute VB_Name = "ex_Hash"
' ======== MD5 hash functions ========
' Shared module version: 20210408
' Tested in: TestCommons
' Depends on:
' Required reference:
Option Private Module
Option Explicit

Public Function MD5AsLong(sText$) As Long
  Dim sMD5$: sMD5 = MD5AsString(sText)
  MD5AsLong = Abs(CLng("&H" & Right(sMD5, 8)))
End Function

Public Function MD5AsString(sText$) As String
' Uses late binding for mscorlib 4.0 64-bit
  If sText = vbNullString Then _
    sText = ""
  Dim oText As Object: Set oText = CreateObject("System.Text.UTF8Encoding")
  Dim inBytes() As Byte: inBytes = oText.GetBytes_4(sText)
  
  Dim oMD5 As Object: Set oMD5 = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
  Dim outBytes() As Byte: outBytes = oMD5.ComputeHash_2(inBytes)
  
  Dim nPos&
  For nPos = 1 To VBA.LenB(outBytes) Step 1
    MD5AsString = MD5AsString & LCase(Right("0" & VBA.Hex(VBA.AscB(VBA.MidB(outBytes, nPos, 1))), 2))
  Next
End Function
