Skip to content
Message Authentication

Message Authentication

Message Authentication Codes (MACs) provide data authenticity and integrity using a shared secret key. They verify that a message came from a holder of the key and hasn’t been tampered with.

What is a MAC?

A MAC is like a “keyed checksum” - it uses a secret key to produce an authentication tag that only someone with the key can generate or verify. Unlike digital signatures, MACs use symmetric keys (same key for generation and verification).

Available MAC Algorithms

HMAC (Recommended)

Hash-based Message Authentication Code

  • Uses a hash function (HMAC-SHA256, HMAC-SHA512, HMAC-SHA3-256)
  • Standardised in FIPS 198-1; also specified in RFC 2104, an Informational RFC

Use HMAC for:

  • API request authentication
  • File integrity verification
  • Message authentication
  • General-purpose MAC needs

CMAC

Cipher-based Message Authentication Code

  • Uses block ciphers (AES-CMAC)
  • Specified in NIST SP 800-38B
  • Good alternative to HMAC

Poly1305

One-time authenticator

  • Designed for high speed
  • Used in ChaCha20-Poly1305
  • Forgery probability about n/2^102 for a 16n-byte message (RFC 8439); each key is used once

Quick Comparison

AlgorithmSecurity StrengthUse CaseRecommended
HMAC-SHA256256-bitGeneral purposePrimary
HMAC-BLAKE3128-bit (BLAKE3 target)Protocols that specify itAlternative
HMAC-SHA512256-bitLonger tagsAlternative
CMAC-AES128-bit tag; at most 2^48 messages per keyBlock cipher preferenceAlternative
Poly1305Forgery about n/2^102With ChaCha20Specialised
GMACForgery about n/2^t for a t-bit tagWith AES-GCMSpecialised

The HMAC figures are the maximums in NIST SP 800-57 Part 1 Rev 5, Table 3, and need a key at least as long as the strength. HMAC-SHA256 and HMAC-SHA512 share the same maximum. HMAC-BLAKE3 is not in that table; 128 bits is the BLAKE3 specification’s security target. GMAC is GCM restricted to data that is not encrypted, so the GCM bounds apply to it.

Common Interface

All MAC algorithms implement the MessageAuthenticationCode interface:

class MessageAuthenticationCode {
public:
    // Set authentication key
    void SetKey(const byte* key, size_t length);

    // Add data to authenticate
    void Update(const byte* input, size_t length);

    // Get MAC tag
    void Final(byte* mac);

    // Reset for new message (keeps key)
    void Restart();

    // Query methods
    unsigned int DigestSize() const;  // MAC tag size
    unsigned int OptimalBlockSize() const;
};

Choosing a MAC Algorithm

For New Systems

Primary Choice: HMAC-SHA256

HMAC<SHA256> hmac(key, keyLen);
  • NIST standard (FIPS 198-1)
  • SHA-256 can use x86 SHA extensions, ARMv8 or Power8 instructions in this library
  • Up to 256-bit security strength with a key of at least that strength

BLAKE3 designs: BLAKE3 keyed mode

BLAKE3 mac(key, 32);  // keyed mode requires exactly 32 bytes of key
  • The BLAKE3 specification says its keyed mode removes the need for a separate construction like HMAC, and needs fewer compressions than HMAC for short messages
  • 128-bit security (BLAKE3’s stated target), below HMAC-SHA256
  • HMAC<BLAKE3> also compiles, for protocols that specify HMAC over BLAKE3

Longer Tags: HMAC-SHA512

HMAC<SHA512> hmac(key, keyLen);
  • 256-bit security strength, the same NIST maximum as HMAC-SHA256
  • Tags up to 64 bytes

For Specific Scenarios

With AES Encryption: Use AES-GCM (provides encryption + MAC together)

With ChaCha20 Encryption: Use ChaCha20-Poly1305 (provides encryption + MAC together)

Block Cipher Preference: Use AES-CMAC

MAC vs Digital Signature

FeatureMACDigital Signature
Key typeSymmetric (shared)Asymmetric (public/private)
VerificationSame keyPublic key
Non-repudiationNoCan support it
Use caseTrusted partiesUntrusted parties

SP 800-57 says a MAC can provide source and integrity authentication when the keys are unique to each pair of entities, and a digital signature can also support a non-repudiation decision.

When to use MAC: Both parties trust each other (API authentication, file integrity)

When to use signatures: Need non-repudiation (software signing, contracts)

Security Best Practices

1. Key Generation

AutoSeededRandomPool rng;
SecByteBlock key(32);  // 256-bit key for HMAC-SHA256
rng.GenerateBlock(key, key.size());

2. Key Length

  • Minimum: 128 bits (16 bytes)
  • Recommended: for HMAC, as long as the hash output: 32 bytes for HMAC-SHA256, 64 bytes for HMAC-SHA512 (see HMAC); BLAKE3 keyed mode takes exactly 32 bytes
  • Never: < 128 bits

We recommend these lengths. SP 800-57 assumes an HMAC key at least as long as the security strength, and RFC 2104 strongly discourages HMAC keys shorter than the hash output.

3. Constant-Time Verification

// WRONG - vulnerable to timing attacks
if (computedMAC == receivedMAC) {
    // Attacker can measure comparison time
}

// CORRECT - check the length (not secret), then compare in constant time
bool valid = receivedMAC.size() == computedMAC.size() &&
    VerifyBufsEqual(reinterpret_cast<const byte*>(computedMAC.data()),
                    reinterpret_cast<const byte*>(receivedMAC.data()),
                    computedMAC.size());

VerifyBufsEqual() compares two equally sized buffers in near constant time and leaves unequal lengths to the caller; the MAC classes’ Verify() and TruncatedVerify() use it.

4. Don’t Use for Passwords

// WRONG - HMAC is fast, so each password guess is cheap
HMAC<SHA256> hmac(salt, saltLen);
hmac.Update(reinterpret_cast<const byte*>(password.data()), password.size());

// CORRECT - use a password hashing function such as Argon2id;
// see the Argon2 page for its DeriveKey() call

5. Key Storage

SecByteBlock key(32);  // Wiped when freed

// NOT: std::string key;  // Leaves key in memory
// NOT: byte key[32];     // Not auto-zeroed

SecByteBlock wipes its memory before freeing it.

Common Patterns

API Request Signing

std::string signRequest(const std::string& method,
                       const std::string& path,
                       const std::string& body,
                       const std::string& timestamp,
                       const SecByteBlock& apiKey) {
    HMAC<SHA256> hmac(apiKey, apiKey.size());

    // The timestamp is signed so the server can refuse old requests; it does not stop replay inside that window
    std::string message = method + "\n" + path + "\n" + timestamp + "\n" + body;
    std::string mac, signature;

    StringSource(message, true,
        new HashFilter(hmac, new StringSink(mac))
    );

    // Encode as hex or base64
    StringSource(mac, true,
        new HexEncoder(new StringSink(signature))
    );

    return signature;
}

File Integrity

std::string computeFileMAC(const std::string& filename,
                           const SecByteBlock& key) {
    HMAC<SHA256> hmac(key, key.size());
    std::string mac, hexMAC;

    FileSource(filename.c_str(), true,
        new HashFilter(hmac, new StringSink(mac))
    );

    StringSource(mac, true,
        new HexEncoder(new StringSink(hexMAC))
    );

    return hexMAC;
}

Encrypt-then-MAC

void authenticatedEncryption(const std::string& plaintext,
                             const SecByteBlock& encKey,
                             const SecByteBlock& macKey,
                             const byte* iv, size_t ivLen,
                             std::string& ciphertext,
                             byte* mac) {
    // 1. Encrypt (iv: fresh random bytes for every message, sent along with the ciphertext)
    // ... encrypt plaintext to ciphertext with encKey and iv ...

    // 2. MAC the IV and the ciphertext (Encrypt-then-MAC)
    HMAC<SHA256> hmac(macKey, macKey.size());
    hmac.Update(iv, ivLen);
    hmac.Update(reinterpret_cast<const byte*>(ciphertext.data()),
                ciphertext.size());
    hmac.Final(mac);  // mac receives HMAC<SHA256>::DIGESTSIZE bytes
}

// Note: In practice, use AES-GCM which combines encryption + MAC

Thread Safety

MAC objects are not thread-safe. Create separate instances per thread:

// WRONG - sharing between threads
HMAC<SHA256> shared_hmac;

// CORRECT - thread-local instances
void threadFunc(const SecByteBlock& key) {
    HMAC<SHA256> hmac(key, key.size());  // Per-thread
    // ... use hmac ...
}

When NOT to Use MACs

Password Hashing

MACs are fast - that’s bad for passwords. Use Argon2:

// WRONG - fast keyed hash of the password
HMAC<SHA256> hmac(salt, saltLen);
hmac.Update(reinterpret_cast<const byte*>(password.data()), password.size());

// CORRECT - Argon2id with a unique random salt; see the Argon2 page

Digital Signatures

MACs require shared secrets. For public verification, use signatures:

// WRONG - both parties need same secret
HMAC<SHA256> hmac(sharedSecret, secretLen);

// CORRECT - public key verification (cryptopp/xed25519.h)
ed25519::Signer signer(privateKey);    // 32-byte private key
ed25519::Verifier verifier(publicKey); // 32-byte public key

Content Addressing

For identifying content without authentication, use hashes:

// If you don't need authentication, just use SHA-256
SHA256 hash;
std::string digest;
StringSource(data, true, new HashFilter(hash, new StringSink(digest)));

Authenticated Encryption (AEAD)

Instead of separate encryption + MAC, use authenticated encryption:

Instead of…Use…
AES-CBC + HMAC-SHA256AES-GCM
AES-CTR + HMAC-SHA256AES-GCM
ChaCha20 + HMACChaCha20-Poly1305

Benefits:

  • Simpler API (one operation)
  • One key and one construction, instead of two to combine correctly

See Also

References

  1. FIPS 198-1: The Keyed-Hash Message Authentication Code (HMAC)
  2. NIST SP 800-57 Part 1 Revision 5: Recommendation for Key Management
  3. RFC 2104: HMAC: Keyed-Hashing for Message Authentication
  4. NIST SP 800-38B: Recommendation for Block Cipher Modes of Operation: The CMAC Mode for Authentication
  5. Bernstein: The Poly1305-AES message-authentication code (2005)
  6. RFC 8439: ChaCha20 and Poly1305 for IETF Protocols
  7. BLAKE3 specification
  8. NIST SP 800-38D: Galois/Counter Mode (GCM) and GMAC