cybersecurity · intermediate · ~15 min

Constant-time byte compare

Avoid the early-exit you'd see in `memcmp`; XOR-accumulate the diff.

Challenge

Compare two byte buffers for equality in constant time, so the running time leaks no information about where they differ.

Task

Implement int ct_equals(const unsigned char *a, const unsigned char *b, size_t n) that compares n bytes of a and b and returns 1 if all bytes are equal, 0 otherwise. The time taken must not depend on the position (or existence) of the first difference. No main — the grader calls it.

Input

  • a, b: two byte buffers, each at least n bytes long.
  • n: the number of bytes to compare (may be 0).

Output

1 if the first n bytes match exactly, 0 if any byte differs.

Example

ct_equals("abcdef", "abcdef", 6)   ->   1
ct_equals("abc", "xbc", 3)         ->   0   (differs at byte 0)
ct_equals("abc", "abd", 3)         ->   0   (differs at byte 2)
ct_equals("", "", 0)               ->   1

Edge cases

  • n = 0: the buffers trivially match; return 1.

Rules

  • Do not early-exit on the first differing byte. Accumulate the XOR of all byte pairs and branchlessly fold it to 0/1.

Input format

Two byte buffers a and b and a length n (n may be 0).

Output format

1 if the first n bytes are equal, 0 otherwise.

Constraints

Constant time: no early exit; accumulate XOR and fold branchlessly.

Starter code

#include <stddef.h>

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

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