Message Authentication Code (MAC)
A message authentication code is a cryptographic tag that verifies both the integrity and authenticity of a message using a shared secret key.
Key Takeaways
- A message authentication code (MAC) is a short cryptographic tag computed from a message and a shared secret key, proving that the message has not been tampered with and was produced by someone who holds the key.
- MACs use symmetric keys (the same secret on both sides), unlike digital signatures which use asymmetric key pairs. This makes MACs faster but unable to provide non-repudiation.
- HMAC-SHA512 is the core primitive behind BIP-32 hierarchical deterministic wallet key derivation, and the Poly1305 MAC secures every message in Lightning Network transport encryption.
What Is a Message Authentication Code?
A message authentication code (MAC) is a fixed-length cryptographic value produced by combining a message with a secret key through a specific algorithm. The recipient, who shares the same key, recomputes the MAC over the received message and compares it to the attached tag. If the values match, the recipient knows two things: the message was not altered in transit (integrity), and the message was created by someone who possesses the secret key (authenticity).
MACs occupy a middle ground between simple error-detection mechanisms and full digital signatures. A checksum or CRC can detect accidental corruption, but an attacker can trivially craft a new message with a matching checksum. A digital signature provides public verifiability and non-repudiation using asymmetric keys, but at a higher computational cost. MACs offer strong tamper protection with the speed of symmetric cryptography: the tradeoff is that both parties must share the same secret key beforehand.
The formal security goal for a MAC is existential unforgeability under chosen-message attack (EUF-CMA): even an adversary who can request valid MACs for arbitrary messages of their choosing cannot forge a valid MAC for any new message.
How It Works
At a high level, a MAC algorithm takes two inputs (a secret key and a variable-length message) and produces a fixed-length tag. The process follows these steps:
- The sender and receiver agree on a shared secret key through a secure channel
- The sender computes
tag = MAC(key, message)and sends both the message and the tag to the receiver - The receiver computes
tag' = MAC(key, message)using the same key and the received message - If
tag == tag', the message is accepted as authentic and unmodified
The security of a MAC rests on the secrecy of the key. Without the key, an attacker cannot produce a valid tag for a forged message, even if they can observe many valid message-tag pairs.
HMAC: Hash-Based MAC
HMAC (Hash-based Message Authentication Code) is the most widely deployed MAC construction, defined in RFC 2104 and standardized by NIST FIPS 198-1. It works with any cryptographic hash function: HMAC-SHA256 produces a 32-byte tag, while HMAC-SHA512 produces a 64-byte tag.
The HMAC formula uses two passes through the hash function with different key-derived padding values:
HMAC(K, message) = H((K' XOR opad) || H((K' XOR ipad) || message))
Where:
K' = key padded (or hashed then padded) to hash block size
ipad = 0x36 repeated for each byte of the block size
opad = 0x5C repeated for each byte of the block size
H = underlying hash function (SHA-256, SHA-512, etc.)
|| = concatenationThe double-hash construction is not redundant. A naive approach like H(key || message) is vulnerable to length-extension attacks with Merkle-Damgard hash functions such as SHA-256. An attacker who knows H(key || message) can compute H(key || message || padding || extra) without knowing the key. HMAC's inner and outer hash passes eliminate this vulnerability by ensuring the intermediate hash result cannot be exploited.
Other MAC Algorithms
While HMAC dominates in protocol design, several other MAC constructions serve specific purposes:
- CMAC (Cipher-based MAC): built on block ciphers like AES, defined in NIST SP 800-38B. Used in hardware-constrained environments where AES acceleration is available but hash functions are not
- Poly1305: a one-time authenticator designed by Daniel Bernstein. It evaluates a polynomial over message chunks modulo the prime 2^130 - 5, producing a 16-byte tag. The key must never be reused: reuse allows an attacker to recover the key through polynomial root-finding
- GMAC (Galois MAC): the authentication-only mode of AES-GCM, defined in NIST SP 800-38D. Extremely fast with hardware AES-NI support but requires a unique nonce per message
- KMAC: a MAC based on the SHA-3 (Keccak) sponge construction, defined in NIST SP 800-185. Unlike HMAC, it does not need the double-hash workaround because SHA-3 is not vulnerable to length-extension attacks
MAC vs Digital Signature vs Checksum
Understanding where MACs fit requires comparing them to the two mechanisms they are most often confused with:
| Property | Checksum / CRC | MAC | Digital Signature |
|---|---|---|---|
| Uses a secret key | No | Yes (symmetric) | Yes (asymmetric) |
| Detects accidental errors | Yes | Yes | Yes |
| Detects malicious tampering | No | Yes | Yes |
| Authenticity | No | Yes (among key holders) | Yes (publicly verifiable) |
| Non-repudiation | No | No | Yes |
| Performance | Very fast | Fast | Slower |
The non-repudiation distinction is critical. Because both parties in a MAC scheme share the same secret key, either one could have generated any given tag. In a dispute, the sender can plausibly deny authorship by claiming the receiver forged the tag, since the receiver holds the same key. Digital signatures solve this: only the private key holder can sign, while anyone with the corresponding public key can verify.
Use Cases
BIP-32 Key Derivation
Bitcoin's BIP-32 standard for hierarchical deterministic wallets relies on HMAC-SHA512 as its fundamental building block. When generating a master key from a seed phrase, BIP-32 computes:
I = HMAC-SHA512(Key = "Bitcoin seed", Data = seed_bytes)
Left 256 bits → master private key
Right 256 bits → master chain codeEvery child key derivation also uses HMAC-SHA512, with the parent chain code as the HMAC key and the parent public key (or private key for hardened derivation) concatenated with the child index as the data. The MAC construction ensures that knowing one child key does not reveal sibling keys or the parent key. The chain code serves as an additional entropy source that prevents key compromise from propagating through the derivation tree.
Lightning Network Transport Encryption
The Lightning Network's encrypted transport layer (BOLT #8) uses ChaCha20-Poly1305, an AEAD (Authenticated Encryption with Associated Data) construction defined in RFC 8439. In this scheme, ChaCha20 provides the stream cipher for confidentiality, while Poly1305 generates a 16-byte authentication tag for each encrypted message.
The protocol follows the Noise framework pattern Noise_XK_secp256k1_ChaChaPoly_SHA256. After a three-act handshake establishes shared symmetric keys via ECDH, every subsequent message is encrypted and authenticated. Poly1305 ensures that any modification to a ciphertext (even a single flipped bit) is detected and rejected. Every 1,000 encryptions, the keys are rotated using HKDF to provide backward secrecy: compromising the current key cannot decrypt previously captured traffic.
TLS and HTTPS
Modern TLS connections (TLS 1.3) exclusively use AEAD cipher suites where the MAC is integrated into the encryption step. The two mandatory cipher suites are AES-128-GCM (using GMAC) and AES-256-GCM. ChaCha20-Poly1305 is also widely supported, especially on devices without hardware AES acceleration. Every HTTPS request you make is authenticated at the record layer by one of these MAC algorithms.
API Authentication
HMAC is widely used to authenticate API requests. The client and server share a secret API key. The client computes an HMAC over the request parameters (method, path, timestamp, body) and includes the tag in a request header. The server recomputes the HMAC to verify the request's authenticity and integrity. This pattern is used by cryptocurrency exchanges, payment processors, and cloud services to secure programmatic access.
Why It Matters for Bitcoin and Payments
MACs are woven into nearly every layer of Bitcoin's security model, even though they operate quietly beneath higher-level abstractions. The key derivation that transforms a seed into millions of addresses, the encrypted peer-to-peer connections between Lightning nodes, and the authenticated communication channels between wallet software and hardware signing devices all depend on MAC algorithms.
For payment infrastructure built on Bitcoin, understanding MACs helps clarify why certain cryptographic choices were made. BIP-32 uses HMAC-SHA512 rather than a simple hash because the MAC construction binds the chain code (acting as a key) to the derivation process, preventing an attacker who obtains a child private key from computing parent or sibling keys. The Lightning Network uses Poly1305 rather than HMAC because its polynomial evaluation is faster for high-throughput message authentication, and the per-message key generation from ChaCha20 naturally satisfies Poly1305's one-time key requirement.
As post-quantum cryptography becomes increasingly relevant, symmetric MAC algorithms like HMAC remain relatively resilient. Grover's algorithm can theoretically halve the effective security of symmetric primitives, but HMAC-SHA256's 256-bit key space still provides 128 bits of post-quantum security, well above practical attack thresholds. This contrasts with elliptic curve-based digital signatures, which Shor's algorithm could break entirely on a sufficiently large quantum computer.
Risks and Considerations
Key Management
A MAC is only as secure as its key. If the shared secret is compromised, an attacker can forge valid tags for arbitrary messages. Unlike digital signatures where compromise of one party's key does not affect the other, a MAC key compromise is bilateral: both sender and receiver lose all security guarantees simultaneously. Secure key distribution, storage, and rotation are essential.
No Non-Repudiation
Because both parties hold the same key, MACs cannot prove which party generated a particular tag. This is acceptable in many protocols (a Lightning node only needs to verify that its peer sent a message, not prove it to a third party), but it makes MACs unsuitable for scenarios requiring legal accountability or dispute resolution. Use digital signatures when non-repudiation is required.
Algorithm-Specific Pitfalls
Different MAC algorithms have different failure modes. Poly1305 keys must never be reused across messages: key reuse allows an attacker to recover the secret through algebraic attacks. GMAC requires unique nonces per message under the same key: a nonce collision leaks the authentication key. HMAC is the most forgiving construction, requiring no nonce and tolerating key reuse across messages, which partly explains its dominance in protocol design.
Tag Verification Timing
MAC verification must use constant-time comparison. A naive byte-by-byte comparison that returns early on the first mismatch leaks information about how many bytes of the tag matched, enabling a timing side-channel attack. Attackers can forge valid tags one byte at a time by measuring response latencies. Cryptographic libraries provide constant-time comparison functions (such as CRYPTO_memcmp or hmac.compare_digest) to prevent this.
This glossary entry is for informational purposes only and does not constitute financial or investment advice. Always do your own research before using any protocol or technology.