Skip to content

HMAC

Header: #include <cryptopp/hmac.h> | Namespace: CryptoPP Since: Crypto++ 2.1 (RFC 2104 form since 2.2)

HMAC (Keyed-Hash Message Authentication Code) provides message authentication using a cryptographic hash function and a secret key shared by the parties. It ensures both data integrity and authenticity - verifying that a message came from a holder of the key and hasn’t been tampered with.

Quick Example

#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    // Secret key: 32 random bytes, as long as the SHA-256 output
    AutoSeededRandomPool rng;
    SecByteBlock key(32);
    rng.GenerateBlock(key, key.size());
    std::string message = "Hello, World!";
    std::string mac, hexOutput;

    // Create HMAC-SHA256
    HMAC<SHA256> hmac(key, key.size());

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

    // Display as hex
    StringSource(mac, true,
        new HexEncoder(new StringSink(hexOutput))
    );

    std::cout << "HMAC-SHA256: " << hexOutput << std::endl;
    return 0;
}

Usage Guidelines

Do:

  • Use HMAC for message authentication (verify sender + detect tampering)
  • Use SHA-256 or better (HMAC-SHA256, HMAC-SHA512, HMAC-SHA3-256)
  • Generate random keys using AutoSeededRandomPool; RFC 2104 says keys need to be chosen at random
  • Use keys at least as long as the hash output (32 bytes for SHA-256, 64 bytes for SHA-512); RFC 2104 strongly discourages shorter keys
  • Use constant-time comparison for MAC verification
  • Store keys securely using SecByteBlock

Avoid:

  • HMAC-MD5 in new designs; RFC 6151 says new protocol designs should not include it
  • HMAC-SHA1 in new designs; we recommend HMAC-SHA256
  • Keys shorter than the hash output, which RFC 2104 says decrease the security strength
  • Using HMAC for password hashing (use Argon2 instead)
  • String comparison for MAC verification (timing attacks)
  • Hardcoded keys (shown in examples for clarity only)

Template Class: HMAC

Template class for creating HMAC with different hash functions.

Template Parameter:

  • T - Hash function class (e.g., SHA256, SHA512, SHA3_256)

Common Instantiations:

  • HMAC<SHA256> - HMAC-SHA256 (recommended)
  • HMAC<SHA512> - HMAC-SHA512 (recommended)
  • HMAC<SHA3_256> - HMAC-SHA3-256
  • HMAC<BLAKE3> - HMAC-BLAKE3; BLAKE3’s own keyed mode removes the need for HMAC
  • HMAC<SHA1> - HMAC-SHA1 (legacy only)

Constants

// For HMAC<SHA256>
static const int DIGESTSIZE = 32;         // MAC output size (SHA256::DIGESTSIZE)
static const int BLOCKSIZE = 64;          // Hash block size (SHA256::BLOCKSIZE)
static const int DEFAULT_KEYLENGTH = 16;  // Default for the key-length argument
static const int MIN_KEYLENGTH = 0;       // Any length up to INT_MAX is accepted

DIGESTSIZE and BLOCKSIZE come from the hash; the key-length limits come from HMAC_Base, which accepts any length from 0 to INT_MAX with a default of 16. The default is not a recommendation: use a key at least as long as the hash output.

Constructors

Default Constructor

HMAC();

Create an HMAC object. Must call SetKey() before use.

Example:

HMAC<SHA256> hmac;
SecByteBlock key(32);  // 256-bit key, wiped when it goes out of scope
// ... generate key ...
hmac.SetKey(key, key.size());

Constructor with Key

HMAC(const byte* key, size_t length = HMAC_Base::DEFAULT_KEYLENGTH);

Create and initialise HMAC with a key.

Parameters:

  • key - Secret key for HMAC
  • length - Key length in bytes (default: 16, recommended: at least the hash output size)

Example:

AutoSeededRandomPool rng;
SecByteBlock key(32);
rng.GenerateBlock(key, key.size());

HMAC<SHA256> hmac(key, key.size());

Methods

SetKey()

void SetKey(const byte* key, size_t length,
            const NameValuePairs& params = g_nullNameValuePairs);

Set or change the HMAC key. A key longer than the hash block size is hashed first, as FIPS 198-1 requires.

Parameters:

  • key - Secret key
  • length - Key length (recommended: at least the hash output size)
  • params - Optional parameters (usually unused)

Thread Safety: Not thread-safe. Don’t call while computing MAC.

Example:

HMAC<SHA256> hmac;
SecByteBlock key(32);
// ... initialize key ...
hmac.SetKey(key, key.size());

Update()

void Update(const byte* input, size_t length);

Add data to the MAC computation.

Parameters:

  • input - Data to authenticate
  • length - Length of data in bytes

Can be called multiple times to process data in chunks.

Example:

HMAC<SHA256> hmac(key, keyLen);
hmac.Update((const byte*)"Part 1", 6);
hmac.Update((const byte*)"Part 2", 6);
// Equivalent to: hmac.Update((const byte*)"Part 1Part 2", 12);

Final()

void Final(byte* mac);

Finalize MAC computation and get result.

Parameters:

  • mac - Output buffer (size: DigestSize() bytes)

Note: Restarts the object for the next message, keeping the key.

Example:

HMAC<SHA256> hmac(key, keyLen);
hmac.Update((const byte*)message.data(), message.size());

byte mac[HMAC<SHA256>::DIGESTSIZE];
hmac.Final(mac);

TruncatedFinal()

void TruncatedFinal(byte* mac, size_t size);

Get a truncated MAC (first size bytes). Throws InvalidArgument if size is larger than DigestSize().

Parameters:

  • mac - Output buffer
  • size - Number of bytes to output (at most DigestSize())

Use case: Some protocols require shorter MACs (e.g., 128-bit instead of 256-bit).

Example:

HMAC<SHA256> hmac(key, keyLen);
hmac.Update((const byte*)data, dataLen);

byte mac[16];  // Truncated to 128 bits
hmac.TruncatedFinal(mac, 16);

Restart()

void Restart();

Reset MAC computation to initial state. Keeps the same key.

Example:

HMAC<SHA256> hmac(key, keyLen);

// Compute MAC for message 1
hmac.Update((const byte*)msg1.data(), msg1.size());
byte mac1[32];
hmac.Final(mac1);

// Reuse same HMAC object for message 2
hmac.Update((const byte*)msg2.data(), msg2.size());
byte mac2[32];
hmac.Final(mac2);

Verify()

bool Verify(const byte* digest);

Verify the MAC computed from prior Update() calls, comparing DigestSize() bytes in constant time with VerifyBufsEqual(). digest must point to DigestSize() bytes; check the length of a received tag before calling.

Parameters:

  • digest - Expected MAC to compare against

Returns: true if MAC matches, false otherwise

Example:

HMAC<SHA256> hmac(key, keyLen);
hmac.Update((const byte*)message.data(), message.size());

if (receivedLen != hmac.DigestSize() || !hmac.Verify(receivedMAC)) {
    std::cerr << "MAC verification failed - message tampered!" << std::endl;
}

VerifyDigest()

bool VerifyDigest(const byte* digest, const byte* input, size_t length);

One-shot verification: computes the MAC over input and compares it with digest in constant time. As with Verify(), digest must point to DigestSize() bytes. TruncatedVerify(digest, digestLength) checks a truncated tag.

Parameters:

  • digest - Expected MAC to compare against
  • input - Message data
  • length - Message length

Returns: true if MAC matches, false otherwise

Example:

HMAC<SHA256> hmac(key, keyLen);
if (receivedLen != hmac.DigestSize() ||
    !hmac.VerifyDigest(receivedMAC, (const byte*)message.data(), message.size())) {
    std::cerr << "MAC verification failed!" << std::endl;
}

DigestSize()

unsigned int DigestSize() const;

Get MAC output size in bytes.

Returns: The hash’s digest size (32 for SHA256, 64 for SHA512, etc.)

AlgorithmName()

std::string AlgorithmName() const;

Get algorithm name.

Returns: "HMAC(" followed by the hash’s name and ")", for example "HMAC(SHA-256)", or "HMAC(BLAKE3-256)" for the default BLAKE3

Complete Example: Request Signing

#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/osrng.h>
#include <iostream>
#include <string>

using namespace CryptoPP;

// The string both sides sign; the timestamp is signed so the server can refuse old requests
std::string signedString(const std::string& method,
                         const std::string& path,
                         const std::string& body,
                         const std::string& timestamp) {
    return method + "\n" + path + "\n" + timestamp + "\n" + body;
}

// Compute the HMAC-SHA256 tag of a request
std::string signRequest(const std::string& method,
                        const std::string& path,
                        const std::string& body,
                        const std::string& timestamp,
                        const SecByteBlock& apiKey) {
    std::string message = signedString(method, path, body, timestamp);

    HMAC<SHA256> hmac(apiKey, apiKey.size());
    std::string mac;

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

    return mac;
}

// Verify a received tag (constant-time)
bool verifyRequest(const std::string& method,
                   const std::string& path,
                   const std::string& body,
                   const std::string& timestamp,
                   const std::string& receivedMAC,
                   const SecByteBlock& apiKey) {
    std::string message = signedString(method, path, body, timestamp);

    // VerifyDigest reads DIGESTSIZE bytes, so reject any other length first
    if (receivedMAC.size() != HMAC<SHA256>::DIGESTSIZE)
        return false;

    HMAC<SHA256> hmac(apiKey, apiKey.size());
    return hmac.VerifyDigest(
        reinterpret_cast<const byte*>(receivedMAC.data()),
        reinterpret_cast<const byte*>(message.data()), message.size()
    );
}

int main() {
    // Generate API key
    AutoSeededRandomPool rng;
    SecByteBlock apiKey(32);
    rng.GenerateBlock(apiKey, apiKey.size());

    const std::string method = "POST";
    const std::string path = "/api/v1/transfer";
    const std::string body = "{\"amount\":100,\"to\":\"user123\"}";
    const std::string timestamp = "2026-11-07T10:15:00Z";

    // Client: sign the request
    std::string mac = signRequest(method, path, body, timestamp, apiKey);

    std::string hex;
    StringSource(mac, true, new HexEncoder(new StringSink(hex)));
    std::cout << "Signature: " << hex << std::endl;

    // Server: verify the request
    bool valid = verifyRequest(method, path, body, timestamp, mac, apiKey);
    std::cout << "Signature valid: " << (valid ? "YES" : "NO") << std::endl;

    return valid ? 0 : 1;
}

The example shows how to compute and verify the tag; it is not a complete request authentication scheme. The timestamp is part of the signed string, so the server can refuse a request whose timestamp is outside a short window. verifyRequest() does not make that check; the caller does, before calling it. Inside the window the same signed request still verifies, so an endpoint that changes state, like the transfer above, also needs a unique request identifier in the signed string that the server records and refuses to accept twice. RFC 9421 draws the same line for HTTP message signatures: a timestamp limits the utility of a captured signature, and a per-message nonce lets the verifier detect a replay.

Complete Example: File Integrity

#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
#include <cryptopp/files.h>
#include <cryptopp/hex.h>
#include <cryptopp/misc.h>
#include <cryptopp/osrng.h>
#include <iostream>
#include <string>

using namespace CryptoPP;

// Compute the HMAC of a file
std::string hmacFile(const std::string& filename, const SecByteBlock& key) {
    HMAC<SHA256> hmac(key, key.size());
    std::string mac;

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

    return mac;
}

// Verify a file against an HMAC computed earlier (constant-time)
bool verifyFile(const std::string& filename,
                const std::string& expectedMAC,
                const SecByteBlock& key) {
    std::string mac = hmacFile(filename, key);

    // The length is not secret: check it before the constant-time compare
    if (expectedMAC.size() != mac.size())
        return false;

    return VerifyBufsEqual(
        reinterpret_cast<const byte*>(mac.data()),
        reinterpret_cast<const byte*>(expectedMAC.data()),
        mac.size()
    );
}

int main() {
    // Generate key
    AutoSeededRandomPool rng;
    SecByteBlock key(32);
    rng.GenerateBlock(key, key.size());

    try {
        // Compute HMAC for an existing file (FileSource throws if it cannot be read)
        std::string mac = hmacFile("document.txt", key);

        std::string hex;
        StringSource(mac, true, new HexEncoder(new StringSink(hex)));
        std::cout << "HMAC: " << hex << std::endl;

        // Later: recompute and compare
        if (!verifyFile("document.txt", mac, key)) {
            std::cerr << "File has been modified" << std::endl;
            return 1;
        }
        std::cout << "File integrity verified" << std::endl;
    } catch (const Exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}

The tag can only be checked with the key that made it. Keep the key for as long as the file needs checking, and keep it where someone who can change the file cannot read it. This example generates a new key on every run.

HMAC Variants

The strengths below are the maximums in NIST SP 800-57 Part 1 Rev 5, Table 3, which assume a key with at least that much entropy.

HMAC-SHA256

HMAC<SHA256> hmac(key, keyLen);
// Output: 256 bits (32 bytes)
// Security strength: up to 256 bits (SP 800-57 Table 3)

Use for: Most applications, API authentication, file integrity

HMAC-SHA512

HMAC<SHA512> hmac(key, keyLen);
// Output: 512 bits (64 bytes)
// Security strength: up to 256 bits, the same maximum as HMAC-SHA256

Use for: Designs already standardised on SHA-512, or that need tags longer than 32 bytes

HMAC-BLAKE3

HMAC<BLAKE3> hmac(key, keyLen);
// Output: 256 bits (32 bytes)
// Security: BLAKE3 targets 128-bit security for all its goals

HMAC-BLAKE3 is not in SP 800-57 Table 3; the BLAKE3 specification targets 128-bit security.

Use for: Protocols that specify HMAC over BLAKE3.

Note: 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. In Crypto++ that is the keyed BLAKE3(key, 32) constructor; see BLAKE3.

HMAC-SHA3-256

HMAC<SHA3_256> hmac(key, keyLen);
// Output: 256 bits (32 bytes)
// Security strength: up to 256 bits (SP 800-57 Table 3)

Use for: Compliance requirements, diversity from SHA-2

HMAC-SHA1 (Legacy)

HMAC<SHA1> hmac(key, keyLen);
// Output: 160 bits (20 bytes)
// Security strength: up to 128 bits (SP 800-57 Table 3)

SP 800-57 rates SHA-1 below 80 bits for digital signatures, which need collision resistance, but still lists HMAC-SHA-1 at up to 128 bits.

Use for: Legacy systems only. Migrate to HMAC-SHA256.

Performance

HMAC<T>::AlgorithmProvider() reports the hash’s implementation. In this library SHA-1 and SHA-256 can use x86 SHA extensions ("SHANI"), ARMv8 instructions, or SSE2, NEON or ARMv7 assembly, and SHA-256 can also use Power8 instructions. SHA-512 has no SHA-NI or ARMv8 path; it uses SSE2, NEON or ARMv7 assembly, or Power8 instructions. Each falls back to "C++".

Security

Security Properties

  • Primitive: HMAC is a message authentication code (MAC) built from a cryptographic hash function. In Crypto++, HMAC<T> takes a hash class with a block size (e.g. SHA256, SHA512); a hash without one makes SetKey() throw InvalidArgument.

  • Tag size:

    • The MAC tag length defaults to the full hash output size (e.g. 32 bytes for SHA-256, 64 bytes for SHA-512).
    • Tags may be truncated. RFC 2104 recommends keeping at least half the hash output and at least 80 bits; SP 800-107 Rev 1 sets a floor of 32 bits.
  • Security level and bounds:

    • SP 800-107 Rev 1 says HMAC’s strength depends on the key, the hash and the tag length.
    • If a system allows 2^t failed verifications per key, the chance of accepting forged data with a tag of L bits is (1/2)^(L-t).
    • SP 800-57 lists HMAC with SHA-256, SHA-384, SHA-512, SHA3-256, SHA3-384 or SHA3-512 at up to 256-bit strength.
  • Key sizes:

    • RFC 2104 strongly discourages keys shorter than the hash output. We recommend a key as long as the hash output: 32 bytes for SHA-256 and 64 bytes for SHA-512.
    • Keys longer than the hash block size are first hashed. SP 800-107 Rev 1 says a key longer than the hash block size is not sensible, because it is replaced by its hash.
  • Deterministic MAC: HMAC is H(K XOR opad, H(K XOR ipad, text)). There is no nonce or IV, so a fixed key and message always give the same tag.

  • Underlying hash assumptions:

    • RFC 2104 needs collision resistance only in the case where the initial value is secret and random, and says the MD5 collision attacks then known did not compromise HMAC-MD5. SP 800-107 Rev 1 does not consider collision attacks on HMAC-SHA-1 practical.
    • Still choose modern, standard hashes (SHA256, SHA512, SHA3_256) and avoid obsolete ones (e.g. MD5, SHA1).
  • Standard: FIPS 198-1; also specified in RFC 2104, an Informational RFC

Security Best Practices

  • Choice of hash function:

    • Prefer HMAC<SHA256> for general use.
    • Use HMAC<SHA512> where you want larger tags or are already standardised on SHA-512.
    • Where you want a BLAKE3 MAC, prefer BLAKE3’s keyed mode, which its specification offers in place of HMAC.
  • Key generation and management:

    • Generate keys with a CSPRNG (e.g. AutoSeededRandomPool) and never derive them from predictable values.
    • Do not reuse the same key across different MAC algorithms (e.g. HMAC and CMAC), or for both MAC and encryption; FIPS 198-1 advises that HMAC keys should not be used for other purposes.
    • Use a KDF or key hierarchy to derive distinct sub-keys per purpose (encryption, MAC, KDF, etc.).
    AutoSeededRandomPool rng;
    SecByteBlock key(32);  // 256-bit key
    rng.GenerateBlock(key, key.size());
  • Tag length:

    • Use at least 128-bit tags for new designs.
    • A 128-bit tag meets the RFC 2104 recommendation of at least half the hash output and at least 80 bits for HMAC-SHA256. HMAC-SHA512 needs a 256-bit tag to keep half of its output.
    • If you truncate further, size the tag and the limit on failed verifications together, as SP 800-107 Rev 1 describes.
  • Verification (constant-time checks):

    • Never compare MAC tags with operator== on std::string or raw buffers.
    • Use Verify(), VerifyDigest(), TruncatedVerify() or VerifyBufsEqual(), which compare in constant time, so that the runtime does not leak how many bytes matched. Check that a received tag has the expected length first.
    // WRONG - timing attack vulnerable
    if (computedMAC == receivedMAC) { /* ... */ }
    
    // CORRECT - check the length, then use VerifyDigest (constant-time)
    HMAC<SHA256> hmac(key, keyLen);
    bool valid = receivedMACLen == hmac.DigestSize() &&
                 hmac.VerifyDigest(receivedMAC, message, msgLen);
  • Key storage:

    SecByteBlock key(32);  // Wiped when freed
    // NOT: byte key[32];   // Leaves key in memory
    

    SecByteBlock wipes its memory before freeing it.

  • Protocol context and replay:

    • Because HMAC is deterministic, you must handle replay protection at the protocol level (sequence numbers, nonces/counters, timestamps, etc.).
    • When authenticating structured messages, include all relevant context in the MAC input (e.g. method, path, headers, direction, protocol version) to prevent tags being replayed in a different context.
  • Usage limits:

    • RFC 2104 recommends refreshing keys periodically.
    • SP 800-107 Rev 1 says to change the key before the number of failed verifications reaches the limit the system allows.
  • Do not use HMAC as a password hash:

    • HMAC is fast by design. For password storage, use a dedicated password hashing / KDF scheme (e.g. Argon2) and keep HMAC for message authentication.
  • No confidentiality:

    • HMAC provides integrity and authenticity only. It does not encrypt or hide the message.
    • For authenticated encryption, use an AEAD construction (e.g. AES-GCM, ChaCha20-Poly1305) rather than “encrypt + HMAC” unless your protocol is explicitly designed and reviewed for that pattern.

Test Vector (RFC 4231 Test Case 1)

#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    // RFC 4231 section 4.2, Test Case 1
    byte key[] = {
        0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
        0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
        0x0b, 0x0b, 0x0b, 0x0b
    };

    std::string message = "Hi There";
    const std::string expected =
        "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7";

    HMAC<SHA256> hmac(key, sizeof(key));
    std::string mac;
    StringSource(message, true,
        new HashFilter(hmac,
            new HexEncoder(new StringSink(mac), false)  // lowercase hex
        )
    );

    std::cout << (mac == expected ? "PASS" : "FAIL") << std::endl;
    return mac == expected ? 0 : 1;
}

The key, data and HMAC-SHA-256 output are Test Case 1 of RFC 4231. Comparing with == is fine here because the expected value is public.

Common Patterns

Encrypt-then-MAC

Correct way to combine encryption and authentication:

#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/filters.h>
#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>

using namespace CryptoPP;

// iv: fresh random AES::BLOCKSIZE bytes for every message, sent along with the ciphertext;
// mac receives HMAC<SHA256>::DIGESTSIZE bytes
void encryptThenMAC(const std::string& plaintext,
                    const SecByteBlock& encKey,
                    const SecByteBlock& macKey,
                    const byte* iv,
                    std::string& ciphertext,
                    byte* mac) {
    // 1. Encrypt
    ciphertext.clear();
    CBC_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(encKey, encKey.size(), iv);

    StringSource(plaintext, true,
        new StreamTransformationFilter(enc,
            new StringSink(ciphertext)
        )
    );

    // 2. MAC the IV and the ciphertext (not the plaintext)
    HMAC<SHA256> hmac(macKey, macKey.size());
    hmac.Update(iv, AES::BLOCKSIZE);
    hmac.Update(reinterpret_cast<const byte*>(ciphertext.data()),
                ciphertext.size());
    hmac.Final(mac);
}

// Note: an AEAD mode such as AES-GCM does encryption and authentication in one step

JWT-style Token

#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
#include <cryptopp/filters.h>
#include <cryptopp/base64.h>

using namespace CryptoPP;

// header and payload must already be base64url-encoded
std::string createToken(const std::string& header,
                       const std::string& payload,
                       const SecByteBlock& key) {
    std::string data = header + "." + payload;

    // Compute signature
    HMAC<SHA256> hmac(key, key.size());
    std::string mac, signature;

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

    // URL-safe alphabet, no padding, no line breaks
    StringSource(mac, true,
        new Base64URLEncoder(new StringSink(signature))
    );

    return data + "." + signature;
}

JWS signs the base64url-encoded header and payload joined by a period, and its base64url encoding omits padding and line breaks. Base64URLEncoder uses the URL-safe alphabet and turns off padding and line breaks by default; Base64Encoder(sink, false) only turns off line breaks.

Thread Safety

Not thread-safe. Create separate HMAC objects for each thread.

// WRONG - sharing between threads
HMAC<SHA256> shared_hmac(key, keyLen);

// CORRECT - one per thread
void threadFunc() {
    HMAC<SHA256> hmac(key, keyLen);  // Thread-local
    // ... use hmac ...
}

Exceptions

  • InvalidKeyLength - Key longer than INT_MAX bytes; any shorter length is accepted
  • InvalidArgument - Truncated size larger than DigestSize(), or a hash without a block size

When to Use HMAC

Use HMAC for:

  1. Request Signing - Signing API requests
  2. File Integrity - Detecting file tampering
  3. Message Authentication - Verifying message sender
  4. Encrypt-then-MAC - Adding authentication to encryption (an AEAD mode such as AES-GCM does both in one step)
  5. Challenge-Response - Authentication protocols
  6. Key Derivation - HKDF is built on HMAC

Don’t use HMAC for:

  1. Password Hashing - Use Argon2 instead
  2. Digital Signatures - Use Ed25519/RSA instead (HMAC requires shared secret)
  3. Checksums - Use hash functions (SHA-256) if authentication not needed

HMAC vs Alternatives

FeatureHMACCMACPoly1305GCM
TypeHash-basedBlock cipher-basedOne-time authenticatorAEAD mode
Key typeSymmetricSymmetricSymmetric, one key per messageSymmetric
Common useAPI authAES-based MACChaCha20-Poly1305AES-GCM
StandardFIPS 198-1, RFC 2104NIST SP 800-38BRFC 8439NIST SP 800-38D

See Also

References

  1. FIPS 198-1: The Keyed-Hash Message Authentication Code (HMAC)
  2. RFC 2104: HMAC: Keyed-Hashing for Message Authentication
  3. RFC 6151: Updated Security Considerations for the MD5 Message-Digest and the HMAC-MD5 Algorithms
  4. RFC 9421: HTTP Message Signatures
  5. NIST SP 800-57 Part 1 Revision 5: Recommendation for Key Management
  6. NIST SP 800-107 Revision 1: Recommendation for Applications Using Approved Hash Algorithms
  7. RFC 4231: Identifiers and Test Vectors for HMAC-SHA-224, HMAC-SHA-256, HMAC-SHA-384, and HMAC-SHA-512
  8. RFC 7515: JSON Web Signature (JWS)