Blog / A02:2021 Cryptographic Failures
A02:2021 · Cryptographic Failures

Turning a MAC into a String quietly breaks the MAC

Raw HMAC bytes got decoded into a default-charset string before comparison. That mangles invalid byte sequences, so two different MACs can compare equal. Enough to defeat the check.

HMAC produces rawbytesbytes decoded astext with…invalid sequencesreplaced…distinct MACs mapto the…integrity checkpasses on…ATTACKER INPUTIMPACToutput is predictable
Attack path · HMAC produces raw bytes → bytes decoded as text with the default charset → invalid sequences replaced or dropped → distinct MACs map to the same string → integrity check passes on a forgery

Raw HMAC bytes got decoded into a default-charset string before comparison. That mangles invalid byte sequences, so two different MACs can compare equal. Enough to defeat the check.

What goes wrong

A helper computed an HMAC and returned it by wrapping the raw bytes in a string using the platform default charset. Bytes are not text. A MAC is arbitrary binary, and most of it is not valid UTF-8 or whatever the platform happened to pick.

When the decoder meets a byte sequence it cannot map, it does not fail. It substitutes a replacement character or drops the sequence. Several different byte arrays can decode to the same string once those substitutions happen. Compare MACs as strings after that, and you have manufactured collisions where the raw bytes had none. An attacker who can nudge inputs toward colliding decodings gets a forged value accepted as authentic.

The fix is to keep the MAC in a form that survives a round trip. Compare the raw bytes directly, or encode with something injective like hex or Base64. Do the comparison in constant time while you are there.

The pattern

Vulnerable
def mac_of(key, data):
    raw = hmac_sha256(key, data)
    return str(raw)          # default charset, lossy

def verify(key, data, expected):
    return mac_of(key, data) == expected
Hardened
def mac_of(key, data):
    return hmac_sha256(key, data)   # keep the raw bytes

def verify(key, data, expected_bytes):
    return constant_time_equal(
        mac_of(key, data), expected_bytes)
How the pipeline adjudicated itPROVEN
ABCDEFGH

Every gate held. The exploit path was reproduced against a negative control, the impact was calibrated, and the finding was signed report-ready.

Ed25519 · per-tenant signing key · gate ledger A–H · verify offline against the published payload hash

Why it matters to you

An integrity check that can be tricked into a false match is worse than no check, because the rest of the system trusts it. If this MAC guards a token, a webhook signature, or the authenticity of a stored record, a collision is an authentication bypass hiding inside a line of glue code that looked like formatting.

Check your own code