← Back to section · Tutorials & Labs

Constant-Time Comparison and Reliable Wiping in C

memcmp's early exit and an optimized-away memset are the two classic traps in C cryptography code: the real semantics of CRYPTO_memcmp and OPENSSL_cleanse, plus every platform's secure-wipe function.

Published 22 November 2026 · 5 min read · PQ Frontier

Constant-Time Comparison and Reliable Wiping in C
AI-generated site artwork
Video explainer · C/C++ cryptography: libraries and implementation

Two Errors That Look Harmless

Two lines in cryptographic C code look obviously correct and are both vulnerabilities. The first is if (memcmp(a, b, n) == 0) used to verify a message authentication code or compare a shared secret. The second is memset(key, 0, len); free(key); — thoughtfully zeroing a secret key before releasing it. The first one’s flaw is time; the second one’s flaw is the compiler. This article explains both mechanisms, gives the real fixes provided by OpenSSL and liboqs, and lists the secure-wipe facilities of every platform in one place. Neither fix needs new algorithm knowledge — what it needs is vigilance about the gap between “compilers and library functions work to general semantics” and “secret data needs special semantics”.

Comparing Secrets: Why memcmp Is Wrong

memcmp has lexicographic semantics, and implementations are allowed — indeed expected — to return at the first differing byte. For ordinary data that is an optimization; for secrets it is a leak: total comparison time is proportional to the position of the first difference, so an attacker who fixes the leading bytes of their input and measures response times repeatedly can guess a correct authentication code byte by byte. Several famous authentication bypasses worked exactly this way. The correct primitive is constant-time comparison: scan all bytes regardless of content before concluding. OpenSSL provides CRYPTO_memcmp, which returns 0 when equal and -1 when not, with an implementation that guarantees no early exit; liboqs provides OQS_MEM_secure_bcmp from the previous article, with the same convention. In use:

#include <openssl/crypto.h>

if (CRYPTO_memcmp(received_tag, expected_tag, TAG_LEN) != 0) {
    /* authentication failed: take the single unified failure path */
}

Two usage details matter. First, the externally visible reaction to failure must be uniform: do not distinguish “wrong length” from “wrong content”, and never leak the difference position in any form — log, error code or timing. Second, a hand-rolled “xor-accumulate” constant-time comparison is not reliable under modern compilers: the compiler may recognize the accumulation loop as an early-exit equivalent, or vectorize it into data-dependent timing. Library functions have a further advantage — their implementations get platform- and compiler-specific treatment and continuous auditing. If you truly must write your own, for example on bare metal, you must disassemble and inspect the generated code afterwards; that is beyond this tutorial’s scope, and the default advice is to always use the library function.

Wiping: Why memset Gets Deleted

The second trap is subtler. The C standard permits dead-store elimination: if a region of memory is written and then released without any intervening read, the compiler may conclude the write cannot affect program behavior and delete it entirely. memset(key, 0, len); free(key); matches this pattern exactly — with optimization enabled, the wipe may simply not exist in the final binary, while source review sees nothing wrong. OpenSSL’s OPENSSL_cleanse exists to plug precisely this hole: its implementation deliberately prevents the compiler from proving the write is dead (the technique varies by platform, including routing the memory set through a function pointer), and its semantic promise is “the wipe definitely happens”. liboqs’ OQS_MEM_cleanse makes the same promise. Usage is identical to an ordinary wipe; what matters is choosing the right function:

#include <openssl/crypto.h>

OPENSSL_cleanse(secret_key, secret_key_len);
free(secret_key);

Beyond library functions, each platform offers an official secure wipe to choose from according to your environment: memset_s from C11 Annex K is the standard answer where the runtime supports it (note that glibc does not provide it); glibc and the BSDs provide explicit_bzero; Windows has SecureZeroMemory; and Linux kernel code has memzero_explicit. A widely circulated folk remedy — writing zeros byte by byte through a volatile pointer — works on most compilers but carries weaker standard-level guarantees than the dedicated functions, and should be the last resort when no platform facility exists. The selection rule in one sentence: prefer the platform-native wipe or the one your crypto library provides, keep folk remedies for genuinely option-less situations, and record the reason in a comment.

Turning Both into Engineering Rules

Knowing the principles is not enough; the rules must enforce themselves in a team. Three suggestions. First, put a ban list in the coding standard and enforce it with static checks: business code must not compare secrets with memcmp directly, and must not call bare memset on key buffers — grep for both names in review and examine every hit. Second, centralize wipe points: converge the entry and exit of every secret’s lifetime into a handful of functions (the RAII guard class from the previous article wipes automatically in its destructor for C++; pure C should use a unified destroy function), rather than scattering wipe calls across every branch. Third, test that wiping really happens: structure the wipe as a small testable function and assert it zeroes a given buffer; for constant-time comparison, sanitizers and ordinary tests cover functional correctness, while timing-level validation needs dedicated tooling (statistical approaches such as dudect) — an advanced topic.

One more idea belongs here: correct use of these two function families cannot be fully backstopped by after-the-fact testing. A timing leak passes every functional test, and an optimized-away wipe shows no anomaly in an ordinary build; both reveal themselves only to an attacker’s measurements and memory forensics. That is why the choices in this article must be made before code is written, not after review: put the designated compare and wipe functions into the coding standard and the project scaffolding from day one, so that whoever follows the template is automatically correct — an order of magnitude cheaper than correcting code line by line afterwards.

Summary

Constant-time comparison and reliable wiping are two faces of one coin: handling secret data must bypass optimizations designed for general data. Compare with CRYPTO_memcmp or OQS_MEM_secure_bcmp; wipe with OPENSSL_cleanse, memset_s, explicit_bzero or another function with a semantic guarantee; and write the ban on memcmp and bare memset into the engineering standard. The next article looks at quality assurance from a different angle: using AddressSanitizer and UBSan to catch out-of-bounds accesses and use-after-free in cryptographic code during testing.

Tags: CConstant TimeOpenSSLSide Channels