cybersecurity · intermediate · ~15 min

Constant-time equality

Avoid timing side-channels in comparisons.

Challenge

Compare two byte arrays without letting the running time reveal where they first differ — the defence against timing side-channels on secrets.

Task

Implement int ct_equal(const unsigned char *a, const unsigned char *b, int n) that returns 1 if the n bytes are equal, else 0, with no early return.

Input

  • a, b: two byte arrays of length n the grader passes.
  • n: the number of bytes to compare.

Output

Returns int: 1 if all n bytes match, else 0.

Example

ct_equal({1,2,3}, {1,2,3}, 3)   ->   1
ct_equal({1,2,3}, {1,9,3}, 3)   ->   0

Edge cases

  • Do not return early on the first mismatch — that leaks how many leading bytes matched.

Rules

  • Accumulate the per-byte differences (e.g. diff |= a[i] ^ b[i]) and test once at the end so the time is independent of where the bytes differ.

Input format

Two byte arrays a and b and their common length n.

Output format

An int: 1 if all n bytes are equal, else 0.

Constraints

No early return — accumulate differences and test once at the end.

Starter code

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

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