← Back to section · Tutorials & Labs

Never Compare a MAC with ==: An Introduction to subtle and Constant-Time Programming

Ordinary equality comparison exits byte by byte and leaks the position of the first mismatching byte. This article explains timing side channels, subtle's Choice, ConstantTimeEq and ConditionallySelectable, and the capability limits of constant-time programming.

Published 22 November 2026 · 6 min read · PQ Frontier

Never Compare a MAC with ==: An Introduction to subtle and Constant-Time Programming
AI-generated site artwork
Video explainer · Rust security development: safe crypto code

How an Innocent-Looking == Becomes an Oracle

When verifying a message authentication code (MAC), the most natural code compares the received tag with the locally computed one using ==. But slice equality comparison short-circuits byte by byte: it returns false the moment the first byte differs, and takes slightly longer if the first five bytes match and only the sixth is wrong. To an attacker, that time difference is an oracle: fix the preceding bytes, iterate over the 256 possibilities for the next byte, and the one that responds more slowly is correct. Advancing byte by byte, a 16-byte MAC takes at most about 16×256 trials to forge — this is not a theoretical attack; multiple historical timing-attack incidents (such as token comparison flaws in early web frameworks) ran on exactly this principle.

There is only one defensive principle: wherever a comparison or selection involves a secret, the execution path and memory-access pattern must not depend on the secret’s value. This is constant-time programming. In the Rust ecosystem, the standard tool is the subtle crate.

subtle’s Core Types

Choice is the foundational type: it wraps a byte that takes only the values 0 or 1, but the type system forbids using it directly as an if condition (it has no implicit conversion to bool). The result of every constant-time decision is a Choice; you must call .unwrap_u8() or bool::from(...) explicitly to turn it into a plain boolean — and that act is deliberately conspicuous, for auditability.

ConstantTimeEq provides the ct_eq method, implemented for integers, byte arrays and slices. The correct way to compare two MACs is:

use subtle::ConstantTimeEq;

fn verify_tag(expected: &[u8; 16], received: &[u8; 16]) -> bool {
    expected.ct_eq(received).into()
}

ct_eq XOR-accumulates all bytes, so the amount of computation is identical no matter which byte differs. The return value is a Choice, converted to bool only at the final step.

ConditionallySelectable provides conditional_select(a, b, choice): it selects between a and b under a Choice without branching. It serves scenarios where “a secret decides which path to take,” such as table lookups and conditional assignment — wherever you are tempted to write if secret { x } else { y }, think of it. The crate also offers ConstantTimeGreater, ConstantTimeLess and other comparison primitives, plus CtOption for “maybe a value” — a small toolbox, but enough to assemble most constant-time logic.

Three High-Frequency Scenarios in Practice

Scenario one: comparing any authentication tag. MACs, HMACs, digest comparisons after signature verification, API-token and password-hash checks — all go through ct_eq. This rule belongs in the team’s coding standard and code-review checklist, because misusing == shows no anomaly whatsoever in functional testing; only the standard can intercept it.

Scenario two: constant-time table lookup. Some algorithms need to index a table by a secret value (such as an S-box lookup). Direct indexing makes the access address depend on the secret, and cache timing may leak the index. The constant-time approach traverses the whole table and uses conditional_select to “pick out” the matching entry — slower, but the access pattern is independent of the secret. Feasible for small tables; large tables call for more systematic techniques such as bitslicing, which is beyond subtle’s scope and needs algorithm-level implementation work.

Scenario three: uniform handling of decryption failure. The implicit rejection of post-quantum KEMs (see the ml-kem article) is at heart the same constant-time idea: whether or not the ciphertext is valid, walk the same computation path and use a constant-time selection to decide which secret to output, rather than erroring out early. subtle’s primitives are exactly the bricks for building such logic.

What a Complete Verification Function Looks Like

Assembling the primitives into deliverable code requires care with length handling. MAC lengths are usually public (determined by the algorithm), so a plain length comparison can come first; but if the length itself is sensitive, it must be folded into the constant-time treatment too. A typical verification function is structured as: confirm both sides have equal length (a plain comparison suffices when length is public), align into a fixed-length buffer, compare everything at once with ct_eq, and combine the result with other checks (version numbers, algorithm identifiers) using bitwise AND on Choice values, converting to bool only after everything has been computed. This “compute everything, then reveal” structure matters: writing it in the short-circuit style of “compare the tag first and return early on failure” reinstalls the oracle by your own hand.

Two more easily missed rules. First, never index an array with a secret, even if the index computation itself has no branches — address leakage is a separate channel, and the constant-time table lookup section above is precisely about it. Second, never do floating-point arithmetic on secrets: floating-point units may take data-dependent time (for example, slow paths for subnormal numbers), so any computation touching secrets in cryptographic implementations should stick to integer paths. Write these two rules into the review checklist alongside ct_eq and the coverage is essentially complete.

The Post-Quantum Connection

Constant-time discipline only grows in post-quantum algorithms. Lattice sampling, accept/reject decisions in rejection sampling, and the implicit-rejection selection in decapsulation all involve secret-dependent branches and accesses; the number of rejection-sampling iterations in ML-DSA signing is itself secret-related, and its implementation must keep the leakage under control. Fortunately, mainstream implementations — whether RustCrypto’s pure-Rust route or PQClean’s C implementations — treat constant time as a design premise, and subtle’s primitives are among the underlying bricks on the Rust side. For application developers the conclusion has two layers: constant time inside algorithm libraries is the library authors’ and auditors’ responsibility, while the three classes of actions in your own code — comparing tags, verifying digests, selecting values by secrets — must be implemented with subtle yourself. Only with both layers in place is the timing channel truly closed.

The Boundary: subtle Is Not a Free Pass

The limits must be stated honestly. subtle guarantees branch-free logic at the source level, but what ultimately runs is machine code produced by the compiler: aggressive optimization may turn branch-free code back into branches, and processor caches, prefetching and speculative execution can introduce timing differences invisible in the source. Acceptance of constant-time code therefore cannot rest on reading source alone; it needs statistical testing as a backstop — for example the dudect approach of comparing timing distributions between two input classes (fixed versus random inputs, testing whether the distributions are distinguishable), run continuously in CI.

The other discipline is scope control: do not try to write all code in constant time — that makes the system unusably slow and unmaintainable. The right approach is to first draw the “secret-related” boundary: only comparisons and selections that touch keys, tags and plaintext content need constant time; everything else is written normally. Aiming subtle at exactly the right spots is the correct way to use this small, sharp crate.

Tags: RustsubtleConstant-TimeSide Channels