Simvik

A constant-time compare

Combine every byte's difference without stopping early, so the time says nothing about the secret. An easy embedded C problem (Side channels and glitches),…

easy · Side channels and glitches · security · timing · bits

A comparison that returns at the first differing byte answers sooner the fewer leading bytes are right: an attacker who times it finds a secret byte by byte.

Write ct_diff(a, b, n): the bitwise OR of a[i] ^ b[i] over all n bytes, without any branch that depends on the data. It is 0 exactly when the buffers are equal, and since every byte goes into it, no byte can be skipped. Then write ct_equal(a, b, n), returning 1 when they are equal and 0 otherwise, from ct_diff.

Starter code

uint8_t ct_diff(const uint8_t *a, const uint8_t *b, unsigned n) {
  for (unsigned i = 0; i < n; i++) {
    if (a[i] != b[i]) return (uint8_t)(a[i] ^ b[i]);
  }
  return 0;
}

int ct_equal(const uint8_t *a, const uint8_t *b, unsigned n) {
  return ct_diff(a, b, n) == 0;
}

Example tests

Equal, and different in the first byte

const uint8_t key[4] = { 0x47, 0x11, 0xA5, 0x3C };
const uint8_t same[4] = { 0x47, 0x11, 0xA5, 0x3C }, first[4] = { 0x46, 0x11, 0xA5, 0x3C };
printf("%d %d\n", ct_equal(key, same, 4), ct_equal(key, first, 4));

Expected output:

1 0

Every byte counts

const uint8_t a[4] = { 0x01, 0x00, 0x00, 0x00 }, b[4] = { 0x00, 0x02, 0x04, 0x08 };
printf("%02X\n", ct_diff(a, b, 4));

Expected output:

0F

Learn it first

  • Side channels and glitches · Timing and power side channels, constant-time code, glitching single decisions, and lockouts that hold.

More Side channels and glitches problems