Skip to content

VBMAN.Hash - Hash Calculation Object

Overview

VBMAN.Hash provides hash calculation functionality based on Windows CryptoAPI, supporting multiple hash algorithms including MD5, SHA1, SHA256, SHA384, and SHA512. It supports hash calculation for strings, byte arrays, and files, with output formats including hexadecimal strings, Base64, and raw byte arrays.

Core Features

  • Multiple Algorithms: Supports MD5, SHA1, SHA256, SHA384, SHA512
  • Multi-format Input: Supports strings, byte arrays, and files
  • UTF8 Support: Perfect support for UTF8 encoded Chinese strings
  • Chain Calls: Fluent API design
  • Flexible Output: Supports Hex, Base64, byte array, and other output formats

Enumerations

CryptoHashAlgorithm

Hash algorithm enumeration

vb
Public Enum CryptoHashAlgorithm
    HASH_ALG_DEFAULT = 0        ' Use class default algorithm (SHA256)
    HASH_ALG_MD5 = 32771        ' MD5 algorithm (128-bit)
    HASH_ALG_SHA1 = 32772       ' SHA1 algorithm (160-bit)
    HASH_ALG_SHA256 = 32780     ' SHA256 algorithm (256-bit)
    HASH_ALG_SHA384 = 32781     ' SHA384 algorithm (384-bit)
    HASH_ALG_SHA512 = 32782     ' SHA512 algorithm (512-bit)
End Enum

CryptoStringEncoding

String encoding enumeration

vb
Public Enum CryptoStringEncoding
    ENCODING_ANSI = 0           ' ANSI encoding
    ENCODING_UTF8 = 1           ' UTF8 encoding (default)
End Enum

Traditional Call Methods

ComputeHash

Calculate hash value of a string (returns hexadecimal string)

vb
Public Function ComputeHash(ByVal Text As String, _
                            Optional ByVal Algorithm As CryptoHashAlgorithm, _
                            Optional ByVal Encoding As CryptoStringEncoding = ENCODING_UTF8) As String

Parameters:

  • Text - The text string to hash
  • Algorithm - Optional parameter, hash algorithm, defaults to class property value (SHA256)
  • Encoding - Optional parameter, string encoding, defaults to UTF8

Returns: Hexadecimal formatted hash string

Example:

vb
' MD5 calculation (default UTF8 encoding)
Dim md5Result As String
md5Result = VBMAN.Hash.ComputeHash("邓伟", HASH_ALG_MD5)
Debug.Print md5Result  ' Output: c518f98015a0e6a6b3ea15c5c7f4a8e2

' MD5 calculation (ANSI encoding)
md5Result = VBMAN.Hash.ComputeHash("邓伟", HASH_ALG_MD5, ENCODING_ANSI)
Debug.Print md5Result

' SHA256 calculation
Dim sha256Result As String
sha256Result = VBMAN.Hash.ComputeHash("Hello World", HASH_ALG_SHA256)
Debug.Print sha256Result

ComputeHashBytesToHex

Calculate hash value of a byte array (returns hexadecimal string)

vb
Public Function ComputeHashBytesToHex(ByRef Data() As Byte, _
                                      Optional ByVal Algorithm As CryptoHashAlgorithm) As String

Example:

vb
Dim bytes() As Byte
bytes = VBMAN.ToolsUtf8.Encode("Hello")

Dim hash As String
hash = VBMAN.Hash.ComputeHashBytesToHex(bytes, HASH_ALG_MD5)
Debug.Print hash

ComputeHashBytes

Calculate hash value of a byte array (returns raw byte array)

vb
Public Function ComputeHashBytes(ByRef Data() As Byte, _
                                 Optional ByVal Algorithm As CryptoHashAlgorithm) As Byte()

Example:

vb
Dim bytes() As Byte
bytes = VBMAN.ToolsUtf8.Encode("Hello")

Dim hashBytes() As Byte
hashBytes = VBMAN.Hash.ComputeHashBytes(bytes, HASH_ALG_SHA256)

ComputeFileHash

Calculate hash value of a file (returns hexadecimal string)

vb
Public Function ComputeFileHash(ByVal FilePath As String, _
                                 Optional ByVal Algorithm As CryptoHashAlgorithm) As String

Description: Directly reads file content in binary mode to calculate hash, without character encoding processing

Example:

vb
' Calculate file MD5
Dim fileMd5 As String
fileMd5 = VBMAN.Hash.ComputeFileHash("C:\\file.txt", HASH_ALG_MD5)
Debug.Print fileMd5

' Calculate file SHA256
Dim fileSha256 As String
fileSha256 = VBMAN.Hash.ComputeFileHash("C:\\file.txt", HASH_ALG_SHA256)
Debug.Print fileSha256

Mode

Set hash algorithm (chain call entry point, optional)

vb
Public Function Mode(ByVal Algorithm As CryptoHashAlgorithm) As cCryptoHash

Description: If this method is not called, defaults to HASH_ALG_SHA256

Example:

vb
' Set algorithm to MD5
VBMAN.Hash.Mode(HASH_ALG_MD5).DataString("hello").ReturnHex()

DataString

Input string data (chain call)

vb
Public Function DataString(ByVal Text As String, _
                          Optional ByVal Encoding As CryptoStringEncoding = ENCODING_UTF8) As cCryptoHash

Example:

vb
' Input UTF8 string
VBMAN.Hash.DataString("你好世界", ENCODING_UTF8).ReturnHex()

' Input ANSI string
VBMAN.Hash.DataString("Hello", ENCODING_ANSI).ReturnHex()

DataBytes

Input byte array data (chain call)

vb
Public Function DataBytes(ByRef Data() As Byte) As cCryptoHash

Example:

vb
Dim bytes() As Byte
bytes = VBMAN.ToolsUtf8.Encode("Hello")

VBMAN.Hash.Mode(HASH_ALG_MD5).DataBytes(bytes).ReturnHex()

Result Return Methods

ReturnHex

Return hexadecimal formatted hash value (chain call)

vb
Public Function ReturnHex(Optional ByVal UpperCase As Boolean = False) As String

Parameters:

  • UpperCase - Optional parameter, whether to use uppercase letters, default False (lowercase)

Example:

vb
' Return lowercase MD5
Dim md5 As String
md5 = VBMAN.Hash.Mode(HASH_ALG_MD5).DataString("邓伟").ReturnHex()
Debug.Print md5  ' c518f98015a0e6a6b3ea15c5c7f4a8e2

' Return uppercase MD5
Dim md5Upper As String
md5Upper = VBMAN.Hash.Mode(HASH_ALG_MD5).DataString("邓伟").ReturnHex(True)
Debug.Print md5Upper  ' C518F98015A0E6A6B3EA15C5C7F4A8E2

ReturnBase64

Return Base64 formatted hash value (chain call)

vb
Public Function ReturnBase64() As String

Example:

vb
Dim base64Hash As String
base64Hash = VBMAN.Hash.Mode(HASH_ALG_SHA256).DataString("Hello").ReturnBase64()
Debug.Print base64Hash

ReturnBytes

Return byte array formatted hash value (chain call)

vb
Public Function ReturnBytes() As Byte()

Example:

vb
Dim hashBytes() As Byte
hashBytes = VBMAN.Hash.Mode(HASH_ALG_MD5).DataString("Hello").ReturnBytes()

' Iterate through byte array
Dim i As Integer
For i = LBound(hashBytes) To UBound(hashBytes)
    Debug.Print Hex(hashBytes(i));
Next

Comprehensive Examples

Example 1: MD5 Hash Calculation (UTF8 Chinese Support)

vb
Private Sub MD5Example()
    ' Basic usage - Calculate MD5 of UTF8 string
    Dim result As String
    
    ' Chinese name MD5 calculation
    result = VBMAN.Hash("邓伟").Mode(HASH_ALG_MD5).ReturnHex()
    Debug.Print "MD5 of 邓伟: " & result
    ' Output: c518f98015a0e6a6b3ea15c5c7f4a8e2
    
    ' Other ways to achieve the same result
    result = VBMAN.Hash.Mode(HASH_ALG_MD5).DataString("邓伟").ReturnHex()
    Debug.Print result
    
    ' Using traditional method
    result = VBMAN.Hash.ComputeHash("邓伟", HASH_ALG_MD5)
    Debug.Print result
End Sub

Example 2: Multiple Algorithms Comparison

vb
Private Sub CompareAlgorithms()
    Dim text As String
    text = "Hello World"
    
    Debug.Print "Original: " & text
    Debug.Print "MD5:    " & VBMAN.Hash.Mode(HASH_ALG_MD5).DataString(text).ReturnHex()
    Debug.Print "SHA1:   " & VBMAN.Hash.Mode(HASH_ALG_SHA1).DataString(text).ReturnHex()
    Debug.Print "SHA256: " & VBMAN.Hash.Mode(HASH_ALG_SHA256).DataString(text).ReturnHex()
    Debug.Print "SHA384: " & VBMAN.Hash.Mode(HASH_ALG_SHA384).DataString(text).ReturnHex()
    Debug.Print "SHA512: " & VBMAN.Hash.Mode(HASH_ALG_SHA512).DataString(text).ReturnHex()
End Sub

Example 3: Password Hash Storage

vb
Private Function HashPassword(password As String, salt As String) As String
    ' Combine password and salt value
    Dim saltedPassword As String
    saltedPassword = password & salt
    
    ' Calculate hash using SHA256
    Dim hash As String
    hash = VBMAN.Hash.Mode(HASH_ALG_SHA256).DataString(saltedPassword).ReturnHex()
    
    HashPassword = hash
End Function

Private Sub TestPasswordHash()
    Dim password As String
    Dim salt As String
    Dim hashed As String
    
    password = "MySecretPassword"
    salt = "random_salt_123"
    
    hashed = HashPassword(password, salt)
    Debug.Print "Password Hash: " & hashed
End Sub

Example 4: File Integrity Verification

vb
Private Function CalculateFileMD5(filePath As String) As String
    On Error GoTo ErrorHandler
    
    ' Calculate file MD5
    Dim md5 As String
    md5 = VBMAN.Hash.ComputeFileHash(filePath, HASH_ALG_MD5)
    
    CalculateFileMD5 = md5
    Exit Function
    
ErrorHandler:
    CalculateFileMD5 = ""
End Function

Private Sub VerifyFileIntegrity()
    Dim filePath As String
    Dim expectedMD5 As String
    Dim actualMD5 As String
    
    filePath = "C:\\important\\document.pdf"
    expectedMD5 = "a1b2c3d4e5f6..."
    
    actualMD5 = CalculateFileMD5(filePath)
    
    If LCase(actualMD5) = LCase(expectedMD5) Then
        Debug.Print "File verification passed"
    Else
        Debug.Print "File verification failed, may have been tampered with"
    End If
End Sub

Example 5: Batch Hash Calculation

vb
Private Sub BatchHashCalculation()
    Dim items As Variant
    items = Array("张三", "李四", "王五", "邓伟")
    
    Dim i As Integer
    For i = LBound(items) To UBound(items)
        Dim name As String
        name = items(i)
        
        ' Calculate MD5
        Dim md5 As String
        md5 = VBMAN.Hash.Mode(HASH_ALG_MD5).DataString(name).ReturnHex()
        
        ' Calculate SHA256
        Dim sha256 As String
        sha256 = VBMAN.Hash.Mode(HASH_ALG_SHA256).DataString(name).ReturnHex()
        
        Debug.Print "Name: " & name
        Debug.Print "  MD5: " & md5
        Debug.Print "  SHA256: " & sha256
    Next i
End Sub

Example 6: Data Pre-processing for Signature

vb
Private Function PrepareDataForSignature(data As String, timestamp As String) As String
    ' Combine data and timestamp
    Dim payload As String
    payload = data & "|" & timestamp
    
    ' Calculate hash using SHA256
    Dim hash As String
    hash = VBMAN.Hash.Mode(HASH_ALG_SHA256).DataString(payload).ReturnHex(True)
    
    PrepareDataForSignature = hash
End Function

Private Sub TestDataSignature()
    Dim data As String
    Dim timestamp As String
    Dim signature As String
    
    data = "order_id=12345&amount=100.00"
    timestamp = CStr(Now())
    
    signature = PrepareDataForSignature(data, timestamp)
    Debug.Print "Data Signature: " & signature
End Sub

Best Practices

  1. UTF8 Chinese Support: When processing Chinese strings, use UTF8 encoding by default to ensure cross-platform consistency
  2. Algorithm Selection:
    • MD5: Fast but low security, suitable for non-security scenarios (e.g., cache keys, simple verification)
    • SHA1: Higher security than MD5, but also not recommended for security scenarios
    • SHA256/SHA384/SHA512: High security, recommended for passwords, digital signatures, and other security scenarios
  3. Chain Calls: Recommended to use chain call method for clearer code
  4. Salt Usage: Password hashes must include random salt to prevent rainbow table attacks
  5. File Hash: When calculating hashes for large files, be mindful of memory usage; the class library automatically handles in chunks

Common MD5 Reference Values

vb
' Empty string MD5
Debug.Print VBMAN.Hash.Mode(HASH_ALG_MD5).DataString("").ReturnHex()
' Result: d41d8cd98f00b204e9800998ecf8427e

' "123456" MD5
Debug.Print VBMAN.Hash.Mode(HASH_ALG_MD5).DataString("123456").ReturnHex()
' Result: e10adc3949ba59abbe56e057f20f883e

' Chinese "你好" MD5
Debug.Print VBMAN.Hash.Mode(HASH_ALG_MD5).DataString("你好").ReturnHex()
' Result: 7eca689f0d3389d9dea66ae112e5cfd7

Algorithm Output Length

AlgorithmOutput Length (Hex)Output Length (Bytes)
MD532 characters16 bytes
SHA140 characters20 bytes
SHA25664 characters32 bytes
SHA38496 characters48 bytes
SHA512128 characters64 bytes

VB6 and LOGO copyright of Microsoft Corporation