cybersecurity · intermediate · ~15 min · safe pentest lab

Compare tokens in constant time

Avoid early-exit branches when comparing secret material.

Challenge

Compare two secret tokens without leaking, through timing, how many leading bytes matched.

Task

Implement int ct_token_match(const char *a, const char *b) that compares two NUL-terminated tokens in constant time with respect to their content. Return 1 if they are equal, 0 otherwise.

Input

  • a, b: NUL-terminated strings the grader passes (e.g. an HMAC, hash, or API token and a candidate).

Output

Returns int: 1 if the two strings are exactly equal, 0 otherwise.

Example

ct_token_match("abc123", "abc123")   ->   1
ct_token_match("abc123", "abc124")   ->   0
ct_token_match("abc",    "abcd")     ->   0   (different length)
ct_token_match("",       "")         ->   1

Edge cases

  • Different lengths must compare unequal (return 0) without short-circuiting on length.
  • Two empty strings are equal → return 1.

Rules

  • Do not return early on the first differing byte — scan a fixed amount of work so the running time does not reveal where the mismatch is. Accumulate differences (e.g. acc |= a[i] ^ b[i]) and test once at the end.

Input format

Two NUL-terminated tokens a and b.

Output format

An int: 1 if the tokens are equal, 0 otherwise.

Constraints

Constant-time compare — no early exit on the first differing byte.

Starter code

#include <stddef.h>

int ct_token_match(const char *a, const char *b) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.