cybersecurity · intermediate · ~12 min · safe pentest lab
The OR-fold pattern that removes data-dependent branching.
Implement:
#include <stddef.h>
int ct_memcmp(const void *a, const void *b, size_t n);
Return 0 if the first n bytes of a and b are equal; non-zero
otherwise. The loop body must touch every byte regardless of where
the first difference is.
break or return inside the loop.n == 0 → return 0 (vacuously equal).a or b (with n > 0) → return 1.acc |= ((unsigned char*)a)[i] ^ ((unsigned char*)b)[i];
then return acc; — non-zero on any mismatch.if (acc) break; to "go faster" — that's
exactly the leak you were defending against.Crypto's most common defence: comparing a tag with memcmp leaks where the mismatch is. The fix is three lines and an OR-fold.
Two const buffers and a byte count.
0 on equal, non-zero otherwise.
No early exit. No data-dependent branching.
#include <stddef.h>
int ct_memcmp(const void *a, const void *b, size_t n) {
/* TODO */
(void)a; (void)b; (void)n;
return -1;
}
Adding if (acc) break;. Returning int from a char * cast (signed widening). Forgetting the n==0 case.
n == 0. NULL with n > 0. Bytes with the high bit set.
O(n) — always exactly n iterations.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.