Skip to content

Useful C Patterns

scauligi edited this page Mar 19, 2018 · 1 revision

All of the following snippets are constant-time C code, and use the macros found here.

// Assignment based on a secret condition
void selecting_things(uint32_t cond) {
  int x = const_select(cond, 42, 137);
}
// Accessing a secret index in a buffer
void use_secret_index(const uint8_t * buf, uint32_t buf_len, uint32_t index) {
  for (int i = 0; i < buf_len; i++) {
    uint32_t mask = const_eq(i, index);
    uint8_t b = const_select(mask, buf[i], 0);
  }
}
// Ending computation "early"
int contains_17(const int * arr, uint32_t arr_len) {
  uint32_t done = 0;
  for (int i = 0; i < arr_len; i++) {
    uint32_t mask = const_eq(arr[i], 17);
    // if mask is "true", then set done to "true"
    // otherwise leave done as-is
    done = done | mask;
  }
  return const_select(done, 1, 0);
}
Clone this wiki locally