cybersecurity · advanced · ~15 min
Prevent timing side-channel attacks by implementing constant-time memory comparison.
Standard library memcmp and strcmp terminate on the first mismatched byte, creating timing side channels that allow attackers to deduce cryptographic secrets and HMAC tokens byte by byte. Constant-time comparison accumulates differences across all bytes.
Implement:
int constant_time_compare(const uint8_t *a, const uint8_t *b, size_t len);
a == NULL or b == NULL, return -1.len == 0, return 0.uint8_t diff = 0.len bytes, compute diff |= (a[i] ^ b[i]) for every index.len bytes.0 if diff == 0 (memory blocks are identical), or 1 if diff != 0 (memory blocks differ).uint8_t hmac1[4] = {0xAA, 0xBB, 0xCC, 0xDD};
uint8_t hmac2[4] = {0xAA, 0xBB, 0xCC, 0xDD};
constant_time_compare(hmac1, hmac2, 4); // returns 0 (identical)
uint8_t hmac3[4] = {0xAA, 0x00, 0xCC, 0xDD};
constant_time_compare(hmac1, hmac3, 4); // returns 1 (mismatched)
a, b: pointers to byte arrays; len: byte count.
Returns 0 if identical, 1 if mismatched, -1 on NULL pointer.
Zero early returns in comparison loop. Bitwise OR accumulator.
#include <stddef.h>
#include <stdint.h>
int constant_time_compare(const uint8_t *a, const uint8_t *b, size_t len) {
(void)a; (void)b; (void)len;
return -1;
}
Breaking early when a difference is found; arithmetic subtraction instead of XOR.
len == 0 returns 0; mismatch at byte 0 takes same execution path as mismatch at byte len-1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.