Skip to content

VBMAN.HashMAC - HMAC Message Authentication Code Object

Overview

VBMAN.HashMAC provides HMAC (Hash-based Message Authentication Code) calculation functionality, supporting HMAC-SHA1 and HMAC-SHA256 algorithms. HMAC uses a secret key to hash data, which can be used for data integrity verification and authentication.

Core Features

  • Standard Algorithms: Supports HMAC-SHA1 and HMAC-SHA256 (RFC 2104 standard)
  • Flexible Key: Supports key input in string, Hex, and Base64 formats
  • UTF8 Support: Perfect support for UTF8 encoded Chinese strings
  • Chain Calls: Fluent API design
  • Multiple Outputs: Supports Hex, Base64, byte array, and other output formats

Enumerations

HMACAlgorithm

HMAC algorithm enumeration

vb
Public Enum HMACAlgorithm
    HMAC_ALG_SHA1 = 32772       ' HMAC-SHA1 algorithm
    HMAC_ALG_SHA256 = 32780     ' HMAC-SHA256 algorithm (default)
End Enum

HMACStringEncoding

String encoding enumeration

vb
Public Enum HMACStringEncoding
    HMAC_ENCODING_ANSI = 0      ' ANSI encoding
    HMAC_ENCODING_UTF8 = 1      ' UTF8 encoding (default)
End Enum

SecretKeyType

Secret key input type enumeration

vb
Public Enum SecretKeyType
    SECRET_KEY_STRING = 0       ' Plain string key
    SECRET_KEY_HEX = 1          ' Hex format key
    SECRET_KEY_BASE64 = 2       ' Base64 format key
End Enum

Traditional Call Methods

SetKey / SetKeyBytes

Set HMAC secret key

vb
' Set key from string
Public Sub SetKey(ByVal KeyString As String, _
                  Optional ByVal Encoding As HMACStringEncoding = HMAC_ENCODING_UTF8)

' Set key from byte array
Public Sub SetKeyBytes(ByRef KeyBytes() As Byte)

Example:

vb
' Use string key
VBMAN.HashMAC.SetKey "my_secret_key"

' Use UTF8 encoded key
VBMAN.HashMAC.SetKey "密钥", HMAC_ENCODING_UTF8

' Use byte array key
Dim keyBytes() As Byte
keyBytes = VBMAN.ToolsUtf8.Encode("secret")
VBMAN.HashMAC.SetKeyBytes keyBytes

Compute

Calculate HMAC of string data (returns hexadecimal string)

vb
Public Function Compute(ByVal Data As String, _
                        ByVal KeyString As String, _
                        Optional ByVal Algorithm As HMACAlgorithm, _
                        Optional ByVal Encoding As HMACStringEncoding = HMAC_ENCODING_UTF8) As String

Parameters:

  • Data - The data to sign
  • KeyString - The key string
  • Algorithm - Optional parameter, HMAC algorithm, defaults to class property value (SHA256)
  • Encoding - Optional parameter, string encoding, defaults to UTF8

Returns: Hexadecimal formatted HMAC string

Example:

vb
' Calculate using HMAC-SHA256
Dim hmac As String
hmac = VBMAN.HashMAC.Compute("Hello World", "my_secret_key", HMAC_ALG_SHA256)
Debug.Print hmac

' Chinese data HMAC calculation
hmac = VBMAN.HashMAC.Compute("邓伟", "密钥", HMAC_ALG_SHA256, HMAC_ENCODING_UTF8)
Debug.Print hmac

ComputeBytesToHex

Calculate HMAC of byte array (returns hexadecimal string)

vb
Public Function ComputeBytesToHex(ByRef Data() As Byte, _
                                  ByRef Key() As Byte, _
                                  Optional ByVal Algorithm As HMACAlgorithm) As String

Example:

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

Dim keyBytes() As Byte
keyBytes = VBMAN.ToolsUtf8.Encode("secret")

Dim hmac As String
hmac = VBMAN.HashMAC.ComputeBytesToHex(dataBytes, keyBytes, HMAC_ALG_SHA256)
Debug.Print hmac

ComputeBytes

Calculate HMAC of byte array (returns byte array)

vb
Public Function ComputeBytes(ByRef Data() As Byte, _
                             ByRef Key() As Byte, _
                             Optional ByVal Algorithm As HMACAlgorithm) As Byte()

Example:

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

Dim keyBytes() As Byte
keyBytes = VBMAN.ToolsUtf8.Encode("secret")

Dim hmacBytes() As Byte
hmacBytes = VBMAN.HashMAC.ComputeBytes(dataBytes, keyBytes, HMAC_ALG_SHA256)

Mode

Set HMAC algorithm (chain call)

vb
Public Function Mode(ByVal Algorithm As HMACAlgorithm) As cCryptoHMAC

Example:

vb
' Set algorithm to HMAC-SHA256
VBMAN.HashMAC.Mode(HMAC_ALG_SHA256).Secret("key").DataString("data").ReturnHex()

Secret

Set secret key (chain call)

vb
Public Function Secret(ByVal KeyString As String, _
                    Optional ByVal KeyType As SecretKeyType = SECRET_KEY_STRING, _
                    Optional ByVal Encoding As HMACStringEncoding = HMAC_ENCODING_UTF8) As cCryptoHMAC

Parameters:

  • KeyString - The key string
  • KeyType - Key input type (STRING/HEX/BASE64), default STRING
  • Encoding - String encoding, default UTF8

Example:

vb
' Plain string key
VBMAN.HashMAC.Secret("my_secret_key").DataString("Hello").ReturnHex()

' Hex format key
VBMAN.HashMAC.Secret("6B6579", SECRET_KEY_HEX).DataString("Hello").ReturnHex()

' Base64 format key
VBMAN.HashMAC.Secret("a2V5", SECRET_KEY_BASE64).DataString("Hello").ReturnHex()

SecretBytes

Set key from byte array (chain call)

vb
Public Function SecretBytes(ByRef KeyBytes() As Byte) As cCryptoHMAC

Example:

vb
Dim keyBytes() As Byte
keyBytes = VBMAN.ToolsUtf8.Encode("secret")

VBMAN.HashMAC.SecretBytes(keyBytes).DataString("Hello").ReturnHex()

DataString

Input string data (chain call)

vb
Public Function DataString(ByVal Text As String, _
                           Optional ByVal Encoding As HMACStringEncoding = HMAC_ENCODING_UTF8) As cCryptoHMAC

Example:

vb
' Input UTF8 string
VBMAN.HashMAC.Secret("key").DataString("你好世界", HMAC_ENCODING_UTF8).ReturnHex()

' Input ANSI string
VBMAN.HashMAC.Secret("key").DataString("Hello", HMAC_ENCODING_ANSI).ReturnHex()

DataBytes

Input byte array data (chain call)

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

Example:

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

VBMAN.HashMAC.Secret("key").DataBytes(dataBytes).ReturnHex()

Result Return Methods

ReturnHex

Return hexadecimal formatted HMAC (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 HMAC
Dim hmac As String
hmac = VBMAN.HashMAC.Mode(HMAC_ALG_SHA256).Secret("key").DataString("邓伟").ReturnHex()
Debug.Print hmac

' Return uppercase HMAC
Dim hmacUpper As String
hmacUpper = VBMAN.HashMAC.Mode(HMAC_ALG_SHA256).Secret("key").DataString("邓伟").ReturnHex(True)
Debug.Print hmacUpper

ReturnBase64

Return Base64 formatted HMAC (chain call)

vb
Public Function ReturnBase64() As String

Example:

vb
Dim base64Hmac As String
base64Hmac = VBMAN.HashMAC.Mode(HMAC_ALG_SHA256).Secret("key").DataString("Hello").ReturnBase64()
Debug.Print base64Hmac

ReturnBytes

Return byte array formatted HMAC (chain call)

vb
Public Function ReturnBytes() As Byte()

Example:

vb
Dim hmacBytes() As Byte
hmacBytes = VBMAN.HashMAC.Mode(HMAC_ALG_SHA256).Secret("key").DataString("Hello").ReturnBytes()

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

Comprehensive Examples

Example 1: Basic HMAC Calculation (UTF8 Chinese Support)

vb
Private Sub BasicHMACExample()
    Dim key As String
    Dim data As String
    Dim hmac As String
    
    ' Chinese key and data
    key = "我的密钥"
    data = "邓伟"
    
    ' HMAC-SHA256 calculation (default UTF8 encoding)
    hmac = VBMAN.HashMAC.Mode(HMAC_ALG_SHA256).Secret(key).DataString(data).ReturnHex()
    Debug.Print "HMAC-SHA256: " & hmac
    
    ' HMAC-SHA1 calculation
    hmac = VBMAN.HashMAC.Mode(HMAC_ALG_SHA1).Secret(key).DataString(data).ReturnHex()
    Debug.Print "HMAC-SHA1: " & hmac
    
    ' Using traditional method
    hmac = VBMAN.HashMAC.Compute(data, key, HMAC_ALG_SHA256)
    Debug.Print "Traditional method: " & hmac
End Sub

Example 2: API Request Signature

vb
Private Function GenerateAPISignature(apiKey As String, apiSecret As String, _
                                     params As String, timestamp As String) As String
    ' Build data to sign
    Dim dataToSign As String
    dataToSign = apiKey & "|" & params & "|" & timestamp
    
    ' Calculate signature using HMAC-SHA256
    Dim signature As String
    signature = VBMAN.HashMAC.Mode(HMAC_ALG_SHA256).Secret(apiSecret).DataString(dataToSign).ReturnHex(True)
    
    GenerateAPISignature = signature
End Function

Private Sub TestAPIRequest()
    Dim apiKey As String
    Dim apiSecret As String
    Dim params As String
    Dim timestamp As String
    Dim signature As String
    
    apiKey = "AKIAIOSFODNN7EXAMPLE"
    apiSecret = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
    params = "action=getUser&id=12345"
    timestamp = CStr(Now())
    
    signature = GenerateAPISignature(apiKey, apiSecret, params, timestamp)
    
    Debug.Print "API Key: " & apiKey
    Debug.Print "Timestamp: " & timestamp
    Debug.Print "Signature: " & signature
End Sub

Example 3: Webhook Signature Verification

vb
Private Function VerifyWebhookSignature(payload As String, signature As String, secret As String) As Boolean
    ' Calculate expected signature
    Dim expectedSignature As String
    expectedSignature = VBMAN.HashMAC.Mode(HMAC_ALG_SHA256).Secret(secret).DataString(payload).ReturnHex()
    
    ' Compare signatures (case-insensitive)
    VerifyWebhookSignature = (LCase(expectedSignature) = LCase(signature))
End Function

Private Sub TestWebhookVerification()
    Dim secret As String
    Dim payload As String
    Dim receivedSignature As String
    Dim isValid As Boolean
    
    secret = "webhook_secret_key"
    payload = "{event:user.created,user_id:12345}"
    receivedSignature = "a1b2c3d4..."  ' Received signature
    
    isValid = VerifyWebhookSignature(payload, receivedSignature, secret)
    
    If isValid Then
        Debug.Print "Webhook signature verification passed"
    Else
        Debug.Print "Webhook signature verification failed"
    End If
End Sub

Example 4: Message Integrity Verification

vb
Private Function CreateMessageWithMAC(message As String, key As String) As String
    ' Calculate HMAC
    Dim mac As String
    mac = VBMAN.HashMAC.Mode(HMAC_ALG_SHA256).Secret(key).DataString(message).ReturnHex()
    
    ' Append MAC to message
    CreateMessageWithMAC = message & "|" & mac
End Function

Private Function VerifyAndExtractMessage(messageWithMAC As String, key As String) As String
    On Error GoTo ErrorHandler
    
    ' Separate message and MAC
    Dim parts() As String
    parts = Split(messageWithMAC, "|")
    
    If UBound(parts) <> 1 Then
        VerifyAndExtractMessage = ""
        Exit Function
    End If
    
    Dim message As String
    Dim receivedMAC As String
    message = parts(0)
    receivedMAC = parts(1)
    
    ' Recalculate MAC
    Dim calculatedMAC As String
    calculatedMAC = VBMAN.HashMAC.Mode(HMAC_ALG_SHA256).Secret(key).DataString(message).ReturnHex()
    
    ' Verify MAC
    If LCase(calculatedMAC) = LCase(receivedMAC) Then
        VerifyAndExtractMessage = message
    Else
        VerifyAndExtractMessage = ""  ' Verification failed
    End If
    Exit Function
    
ErrorHandler:
    VerifyAndExtractMessage = ""
End Function

Private Sub TestMessageIntegrity()
    Dim key As String
    Dim originalMessage As String
    Dim messageWithMAC As String
    Dim extractedMessage As String
    
    key = "shared_secret_key"
    originalMessage = "Important data: Transfer amount 1000 yuan"
    
    ' Sender creates message with MAC
    messageWithMAC = CreateMessageWithMAC(originalMessage, key)
    Debug.Print "Message with MAC: " & messageWithMAC
    
    ' Receiver verifies and extracts message
    extractedMessage = VerifyAndExtractMessage(messageWithMAC, key)
    
    If extractedMessage <> "" Then
        Debug.Print "Message verification passed: " & extractedMessage
    Else
        Debug.Print "Message verification failed"
    End If
End Sub

Best Practices

  1. Key Security: HMAC keys should be stored securely, do not hardcode them in code
  2. Algorithm Selection: HMAC-SHA256 is recommended for higher security
  3. UTF8 Encoding: Use UTF8 encoding by default when processing Chinese strings
  4. Key Length: Key length should be at least 32 bytes (256 bits)
  5. Signature Comparison: Use constant-time comparison when comparing HMAC values to prevent timing attacks
  6. Chain Calls: Recommended to use chain call method for clearer code

HMAC vs Regular Hash

FeatureHMACRegular Hash (MD5/SHA)
KeyRequires keyNo key required
PurposeAuthentication, integrity verificationData verification, fingerprinting
SecurityHigh (depends on key)Medium (tamper-proof only)
Use CasesAPI signatures, TokensFile verification, Cache keys

Common Application Scenarios

  1. API Request Signing: Verify request source and integrity
  2. Webhook Verification: Confirm authenticity of callback notifications
  3. Message Authentication: Ensure messages have not been tampered with
  4. Token Generation: Create signed temporary tokens
  5. File Transfer: Verify integrity of transferred files

VB6 and LOGO copyright of Microsoft Corporation