CMAC
Header: #include <cryptopp/cmac.h> | Namespace: CryptoPP
Since: Crypto++ 5.6.0
Thread Safety: Not thread-safe per instance; use separate instances per thread
CMAC (Cipher-based Message Authentication Code) is a block cipher-based MAC specified in NIST SP 800-38B. SP 800-38B notes that CMAC may suit systems where an approved block cipher is more readily available than an approved hash function, and it covers CMAC with AES and TDEA. In Crypto++, CMAC<T> takes the block cipher as its template parameter.
Quick Example
#include <cryptopp/cmac.h>
#include <cryptopp/aes.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/osrng.h>
#include <iostream>
int main() {
using namespace CryptoPP;
AutoSeededRandomPool rng;
// Generate 128-bit key (AES::DEFAULT_KEYLENGTH = 16 bytes)
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
rng.GenerateBlock(key, key.size());
// Compute CMAC
std::string message = "Message to authenticate";
std::string mac;
CMAC<AES> cmac(key, key.size());
StringSource(message, true,
new HashFilter(cmac,
new HexEncoder(new StringSink(mac))
)
);
// 32 hex characters = 16-byte tag
std::cout << "AES-CMAC: " << mac << std::endl;
return 0;
}Usage Guidelines
- Use AES-CMAC for new applications
- Use a key size the cipher accepts (16, 24 or 32 bytes for AES)
- Generate keys uniformly at random, for example with
AutoSeededRandomPool - Use constant-time comparison for verification (
Verify()orTruncatedVerify())
- Don’t use CMAC for password hashing (use Argon2)
- Don’t use 64-bit block ciphers such as TDEA for new designs; SP 800-38B limits a TDEA key to far fewer messages than an AES key
- Don’t expose timing information during verification
- Don’t use the same key for encryption and CMAC; SP 800-38B requires the key to be used only for CMAC
Constructor
// Default constructor (must call SetKey later)
CMAC();
// Constructor with key
CMAC(const byte* key, size_t length = SameKeyLengthAs<T>::DEFAULT_KEYLENGTH);Parameters
| Parameter | Type | Description |
|---|---|---|
key | const byte* | Pointer to key bytes |
length | size_t | Key length (16, 24, or 32 bytes for AES) |
CMAC<T> takes its key lengths from the cipher; AES accepts keys of 16 to 32 bytes in steps of 8.
Methods
SetKey
void SetKey(const byte* key, size_t length,
const NameValuePairs& params = g_nullNameValuePairs);Sets or changes the authentication key. Throws InvalidKeyLength if the cipher does not accept the length.
Update
void Update(const byte* input, size_t length);Adds data to the MAC computation.
Final
void Final(byte* mac);Computes the final MAC tag and restarts the object for the next message.
TruncatedFinal
void TruncatedFinal(byte* mac, size_t size);Computes a truncated MAC tag. Throws InvalidArgument if size is larger than DigestSize().
Verify
bool Verify(const byte* mac);Finishes the current message and compares the full tag in constant time using VerifyBufsEqual().
TruncatedVerify
bool TruncatedVerify(const byte* mac, size_t length);Verifies a truncated MAC tag of length bytes in constant time. Throws InvalidArgument if length is larger than DigestSize(). The four-argument VerifyTruncatedDigest(mac, length, input, inputLength) does the Update() and the check in one call.
Restart
void Restart();Resets for a new message and keeps the key and subkeys.
DigestSize
unsigned int DigestSize() const;Returns the MAC tag size, which is the cipher’s block size: 16 bytes for AES-CMAC.
Complete Examples
Example 1: Basic AES-CMAC
#include <cryptopp/cmac.h>
#include <cryptopp/aes.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/osrng.h>
#include <iostream>
int main() {
using namespace CryptoPP;
AutoSeededRandomPool rng;
// Generate key
SecByteBlock key(AES::DEFAULT_KEYLENGTH); // 128-bit
rng.GenerateBlock(key, key.size());
std::string message = "The quick brown fox jumps over the lazy dog";
// Method 1: Pipeline
std::string mac1;
CMAC<AES> cmac1(key, key.size());
StringSource(message, true,
new HashFilter(cmac1,
new HexEncoder(new StringSink(mac1))
)
);
// Method 2: Direct API
CMAC<AES> cmac2(key, key.size());
cmac2.Update((const byte*)message.data(), message.size());
byte mac2[AES::BLOCKSIZE];
cmac2.Final(mac2);
std::cout << "AES-CMAC: " << mac1 << std::endl;
return 0;
}Example 2: CMAC Verification
#include <cryptopp/cmac.h>
#include <cryptopp/aes.h>
#include <cryptopp/osrng.h>
#include <iostream>
using namespace CryptoPP;
// mac must point to AES::BLOCKSIZE (16) bytes
bool verifyMessage(const std::string& message,
const byte* mac,
const SecByteBlock& key) {
CMAC<AES> cmac(key, key.size());
cmac.Update((const byte*)message.data(), message.size());
return cmac.Verify(mac); // Constant-time comparison
}
int main() {
AutoSeededRandomPool rng;
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
rng.GenerateBlock(key, key.size());
std::string message = "Authentic message";
// Compute MAC
CMAC<AES> cmac(key, key.size());
cmac.Update((const byte*)message.data(), message.size());
byte mac[AES::BLOCKSIZE];
cmac.Final(mac);
// Verify MAC
if (verifyMessage(message, mac, key)) {
std::cout << "Message is authentic" << std::endl;
} else {
std::cerr << "Message has been tampered with!" << std::endl;
return 1;
}
// Tamper with message
std::string tamperedMessage = "Tampered message";
if (verifyMessage(tamperedMessage, mac, key)) {
std::cerr << "Tampering was not detected!" << std::endl;
return 1;
}
std::cout << "Tampering detected!" << std::endl;
return 0;
}Example 3: File Authentication
#include <cryptopp/cmac.h>
#include <cryptopp/aes.h>
#include <cryptopp/files.h>
#include <cryptopp/filters.h>
#include <cryptopp/misc.h>
using namespace CryptoPP;
// Compute CMAC and return raw bytes; mac must hold AES::BLOCKSIZE bytes
void computeFileCMAC(const std::string& filename,
const SecByteBlock& key,
byte* mac) {
CMAC<AES> cmac(key, key.size());
FileSource(filename.c_str(), true,
new HashFilter(cmac,
new ArraySink(mac, AES::BLOCKSIZE)
)
);
}
// Verify using constant-time comparison; expectedMAC must hold
// AES::BLOCKSIZE bytes
bool verifyFileCMAC(const std::string& filename,
const byte* expectedMAC,
const SecByteBlock& key) {
byte computed[AES::BLOCKSIZE];
computeFileCMAC(filename, key, computed);
// Constant-time verification
return VerifyBufsEqual(computed, expectedMAC, sizeof(computed));
}HashFilter finalises the MAC when the source ends, which restarts the object, so calling cmac.Verify() after the pipeline would check the tag of an empty message. Compute the tag into a buffer and compare it as above.
Example 4: API Request Signing
#include <cryptopp/cmac.h>
#include <cryptopp/aes.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <sstream>
using namespace CryptoPP;
std::string signAPIRequest(const std::string& method,
const std::string& path,
const std::string& timestamp,
const std::string& body,
const SecByteBlock& apiKey) {
// Create canonical string
std::ostringstream canonical;
canonical << method << "\n"
<< path << "\n"
<< timestamp << "\n"
<< body;
std::string signature;
CMAC<AES> cmac(apiKey, apiKey.size());
StringSource(canonical.str(), true,
new HashFilter(cmac,
new HexEncoder(new StringSink(signature))
)
);
return signature;
}
// Usage:
// std::string sig = signAPIRequest("POST", "/api/v1/data", "2025-01-15T12:00:00Z", body, key);
// Set header: X-Signature: sig
Example 5: 256-bit Key CMAC
#include <cryptopp/cmac.h>
#include <cryptopp/aes.h>
#include <cryptopp/osrng.h>
int main() {
using namespace CryptoPP;
AutoSeededRandomPool rng;
// 256-bit key for AES-256-CMAC
SecByteBlock key(AES::MAX_KEYLENGTH); // 32 bytes
rng.GenerateBlock(key, key.size());
CMAC<AES> cmac(key, key.size());
std::string message = "High security message";
cmac.Update((const byte*)message.data(), message.size());
byte mac[AES::BLOCKSIZE];
cmac.Final(mac);
return 0;
}Example 6: Truncated CMAC
#include <cryptopp/cmac.h>
#include <cryptopp/aes.h>
#include <cryptopp/osrng.h>
#include <iostream>
// Some protocols use truncated MACs (e.g., 8 bytes instead of 16)
int main() {
using namespace CryptoPP;
AutoSeededRandomPool rng;
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
rng.GenerateBlock(key, key.size());
std::string message = "Message";
CMAC<AES> cmac(key, key.size());
cmac.Update((const byte*)message.data(), message.size());
// Get only 8 bytes (64 bits) of MAC
byte truncatedMAC[8];
cmac.TruncatedFinal(truncatedMAC, sizeof(truncatedMAC));
// Verify truncated MAC (TruncatedFinal already restarted the object)
cmac.Update((const byte*)message.data(), message.size());
bool valid = cmac.TruncatedVerify(truncatedMAC, sizeof(truncatedMAC));
std::cout << "Valid: " << (valid ? "yes" : "no") << std::endl;
return valid ? 0 : 1;
}SP 800-38B says a tag of at least 64 bits suits most applications, and a shorter tag needs a risk analysis and a limit on failed verifications.
Example 7: Incremental Update
#include <cryptopp/cmac.h>
#include <cryptopp/aes.h>
#include <cryptopp/osrng.h>
void incrementalCMAC() {
using namespace CryptoPP;
AutoSeededRandomPool rng;
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
rng.GenerateBlock(key, key.size());
CMAC<AES> cmac(key, key.size());
// Process data in chunks
std::string part1 = "First part of ";
std::string part2 = "the message to ";
std::string part3 = "authenticate";
cmac.Update((const byte*)part1.data(), part1.size());
cmac.Update((const byte*)part2.data(), part2.size());
cmac.Update((const byte*)part3.data(), part3.size());
byte mac[AES::BLOCKSIZE];
cmac.Final(mac);
// Same result as hashing the full message at once
}CMAC vs HMAC
| Feature | CMAC | HMAC |
|---|---|---|
| Based on | Block cipher (AES) | Hash function (SHA-2, SHA-3) |
| Output size | Block size (16 bytes for AES) | Hash size (32 for SHA-256) |
| Key size | Cipher key size (16 to 32 bytes for AES) | Any length; keys longer than the hash block are hashed first |
| Standard | NIST SP 800-38B | FIPS 198-1; also specified in RFC 2104 |
When to use CMAC:
- Already using AES for encryption, and you want to avoid adding a hash function
- A NIST-approved MAC is required; CMAC with AES is approved in SP 800-38B
When to use HMAC:
- General-purpose MAC
- A hash function is already available in your design
Hardware Detection
CMAC<T>::AlgorithmProvider() reports the underlying cipher’s implementation. For AES it returns "AESNI", "SSE2", "ARMv8", "ARMv7", "Power8" or "C++".
#include <cryptopp/cmac.h>
#include <cryptopp/aes.h>
#include <iostream>
void checkHardwareSupport() {
using namespace CryptoPP;
CMAC<AES> cmac;
std::cout << "AES provider: " << cmac.AlgorithmProvider() << std::endl;
// Output:
// "AESNI" - x86 AES-NI instructions
// "ARMv8" - ARMv8 Cryptography Extensions
// "C++" - portable implementation
}Security Properties
Primitive: CMAC is a MAC built from a block cipher. In Crypto++,
CMAC<AES>is the most common instantiation.Block and tag size:
- For
CMAC<AES>the block size is 128 bits. - The MAC tag can be up to 128 bits (16 bytes); shorter tags are supported via truncation.
- For
Security level and bounds (SP 800-38B appendices A and B):
- A randomly guessed tag of Tlen bits is valid with probability 1 in 2^Tlen.
- A collision between the untruncated MACs of two messages lets an attacker forge a MAC for a new message. With AES, a collision is expected among about 2^64 messages.
- For general-purpose applications, SP 800-38B recommends at most 2^48 messages per AES key (and 2^21 for TDEA). Where higher confidence is required, it recommends at most 2^48 message blocks per AES key.
- The collision probability depends on the message span relative to the block size, so a larger AES key does not raise these limits.
Key sizes:
- AES keys: 128, 192, or 256 bits, all supported by
CMAC<AES>.
- AES keys: 128, 192, or 256 bits, all supported by
Deterministic MAC: MAC generation takes only the key, the message and the tag length. There is no nonce, so a fixed key and message always give the same tag.
Security Notes
Message and data limits:
- Keep each key within the SP 800-38B message-span limits above; a cryptoperiod can enforce them.
- For 64-bit block ciphers such as TDEA the recommended limit is 2^21 messages per key, so treat them as legacy and use them only for compatibility.
Tag length choices:
- Use a 128-bit tag for new designs unless there is a strong reason to truncate.
- SP 800-38B considers at least 64 bits sufficient for most applications. Shorter tags need a careful risk analysis and a limit on how often verification may fail under a key.
- The tag length must stay fixed for every use of a given key.
Key separation:
- SP 800-38B requires the key to be used only for CMAC with the chosen cipher. Do not reuse it for encryption or for another MAC.
- Derive separate sub-keys for encryption, CMAC, and any other MAC or KDF using a key hierarchy appropriate for your protocol.
Key quality and storage:
- The key must be secret and generated uniformly at random, or close to it, for example via
AutoSeededRandomPool. - Protect keys according to your application’s key-management policy.
- The key must be secret and generated uniformly at random, or close to it, for example via
Verification:
- Perform tag checks in constant time.
- In Crypto++, use
Verify(),TruncatedVerify()orVerifyBufsEqual(), rather thanoperator==on strings or buffers.
No confidentiality:
- CMAC provides integrity and authenticity only. It does not encrypt or hide the message.
- For authenticated encryption, use AES-GCM or ChaCha20-Poly1305 rather than “encrypt + CMAC” unless your protocol is explicitly designed and reviewed.
Replay and protocol context:
- CMAC does not detect replayed messages; SP 800-38B appendix C leaves that to the protocol, for example with sequence numbers or timestamps inside the authenticated message.
- When authenticating structured data, include all relevant context (protocol version, direction, headers, etc.) in the CMAC input so that tags cannot be replayed out of context.
Thread Safety
CMAC objects are not thread-safe:
// WRONG - shared across threads
CMAC<AES> sharedCMAC(key, keyLen);
// CORRECT - per-thread
void computeInThread(const std::string& message, const SecByteBlock& key) {
CMAC<AES> cmac(key, key.size());
cmac.Update((const byte*)message.data(), message.size());
byte mac[AES::BLOCKSIZE];
cmac.Final(mac);
}Error Handling
#include <cryptopp/cmac.h>
#include <cryptopp/aes.h>
#include <iostream>
using namespace CryptoPP;
void safeCMAC(const SecByteBlock& key, const std::string& message) {
try {
// Key size validation happens in SetKey
CMAC<AES> cmac(key, key.size());
cmac.Update((const byte*)message.data(), message.size());
byte mac[AES::BLOCKSIZE];
cmac.Final(mac);
} catch (const InvalidKeyLength& e) {
std::cerr << "Invalid key length: " << e.what() << std::endl;
// AES requires 16, 24, or 32 byte keys
} catch (const Exception& e) {
std::cerr << "CMAC error: " << e.what() << std::endl;
}
}Alternative Ciphers
CMAC<T> accepts block ciphers with an 8-, 16- or 32-byte block. SP 800-38B covers only AES and TDEA; other ciphers are outside that standard.
#include <cryptopp/cmac.h>
#include <cryptopp/des.h>
#include <cryptopp/camellia.h>
using namespace CryptoPP;
// Each MAC gets its own key; never share one key between algorithms
void otherCiphers(const byte* desKey, const byte* camelliaKey) {
// 3DES-CMAC (legacy, not recommended for new applications)
CMAC<DES_EDE3> cmac3des(desKey, DES_EDE3::DEFAULT_KEYLENGTH);
// Camellia-CMAC (not covered by SP 800-38B)
CMAC<Camellia> cmacCamellia(camelliaKey, Camellia::DEFAULT_KEYLENGTH);
}See Also
- HMAC - Hash-based MAC
- Poly1305 - One-time authenticator
- AES-GCM - Authenticated encryption with built-in MAC
- HashFilter - Pipeline filter for MACs
- Security Concepts - MAC best practices