cybersecurity · intermediate · ~15 min
Avoid the early-exit you'd see in `memcmp`; XOR-accumulate the diff.
Compare two byte buffers for equality in constant time, so the running time leaks no information about where they differ.
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.
a, b: two byte buffers, each at least n bytes long.n: the number of bytes to compare (may be 0).1 if the first n bytes match exactly, 0 if any byte differs.
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
n = 0: the buffers trivially match; return 1.0/1.Two byte buffers a and b and a length n (n may be 0).
1 if the first n bytes are equal, 0 otherwise.
Constant time: no early exit; accumulate XOR and fold branchlessly.
#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.