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
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 EnumCryptoStringEncoding
String encoding enumeration
Public Enum CryptoStringEncoding
ENCODING_ANSI = 0 ' ANSI encoding
ENCODING_UTF8 = 1 ' UTF8 encoding (default)
End EnumTraditional Call Methods
ComputeHash
Calculate hash value of a string (returns hexadecimal string)
Public Function ComputeHash(ByVal Text As String, _
Optional ByVal Algorithm As CryptoHashAlgorithm, _
Optional ByVal Encoding As CryptoStringEncoding = ENCODING_UTF8) As StringParameters:
Text- The text string to hashAlgorithm- Optional parameter, hash algorithm, defaults to class property value (SHA256)Encoding- Optional parameter, string encoding, defaults to UTF8
Returns: Hexadecimal formatted hash string
Example:
' 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 sha256ResultComputeHashBytesToHex
Calculate hash value of a byte array (returns hexadecimal string)
Public Function ComputeHashBytesToHex(ByRef Data() As Byte, _
Optional ByVal Algorithm As CryptoHashAlgorithm) As StringExample:
Dim bytes() As Byte
bytes = VBMAN.ToolsUtf8.Encode("Hello")
Dim hash As String
hash = VBMAN.Hash.ComputeHashBytesToHex(bytes, HASH_ALG_MD5)
Debug.Print hashComputeHashBytes
Calculate hash value of a byte array (returns raw byte array)
Public Function ComputeHashBytes(ByRef Data() As Byte, _
Optional ByVal Algorithm As CryptoHashAlgorithm) As Byte()Example:
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)
Public Function ComputeFileHash(ByVal FilePath As String, _
Optional ByVal Algorithm As CryptoHashAlgorithm) As StringDescription: Directly reads file content in binary mode to calculate hash, without character encoding processing
Example:
' 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 fileSha256Chain Call Methods (Recommended)
Mode
Set hash algorithm (chain call entry point, optional)
Public Function Mode(ByVal Algorithm As CryptoHashAlgorithm) As cCryptoHashDescription: If this method is not called, defaults to HASH_ALG_SHA256
Example:
' Set algorithm to MD5
VBMAN.Hash.Mode(HASH_ALG_MD5).DataString("hello").ReturnHex()DataString
Input string data (chain call)
Public Function DataString(ByVal Text As String, _
Optional ByVal Encoding As CryptoStringEncoding = ENCODING_UTF8) As cCryptoHashExample:
' 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)
Public Function DataBytes(ByRef Data() As Byte) As cCryptoHashExample:
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)
Public Function ReturnHex(Optional ByVal UpperCase As Boolean = False) As StringParameters:
UpperCase- Optional parameter, whether to use uppercase letters, default False (lowercase)
Example:
' 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 ' C518F98015A0E6A6B3EA15C5C7F4A8E2ReturnBase64
Return Base64 formatted hash value (chain call)
Public Function ReturnBase64() As StringExample:
Dim base64Hash As String
base64Hash = VBMAN.Hash.Mode(HASH_ALG_SHA256).DataString("Hello").ReturnBase64()
Debug.Print base64HashReturnBytes
Return byte array formatted hash value (chain call)
Public Function ReturnBytes() As Byte()Example:
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));
NextComprehensive Examples
Example 1: MD5 Hash Calculation (UTF8 Chinese Support)
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 SubExample 2: Multiple Algorithms Comparison
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 SubExample 3: Password Hash Storage
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 SubExample 4: File Integrity Verification
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 SubExample 5: Batch Hash Calculation
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 SubExample 6: Data Pre-processing for Signature
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 SubBest Practices
- UTF8 Chinese Support: When processing Chinese strings, use UTF8 encoding by default to ensure cross-platform consistency
- 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
- Chain Calls: Recommended to use chain call method for clearer code
- Salt Usage: Password hashes must include random salt to prevent rainbow table attacks
- File Hash: When calculating hashes for large files, be mindful of memory usage; the class library automatically handles in chunks
Common MD5 Reference Values
' 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: 7eca689f0d3389d9dea66ae112e5cfd7Algorithm Output Length
| Algorithm | Output Length (Hex) | Output Length (Bytes) |
|---|---|---|
| MD5 | 32 characters | 16 bytes |
| SHA1 | 40 characters | 20 bytes |
| SHA256 | 64 characters | 32 bytes |
| SHA384 | 96 characters | 48 bytes |
| SHA512 | 128 characters | 64 bytes |