Naruto
9/4/2017 - 2:12 AM

counter.c

#include <stdio.h>
#include <stdint.h>

/* increment counter (128-bit int) by 1 */
static uint8_t *ctr128_inc(uint8_t *counter) {
    uint32_t n=16;
    uint8_t  c;
    do {
        --n;
        c = counter[n];
        ++c;
        counter[n] = c;
        if (c) return counter;
    } while (n);

    return counter;
}

static uint8_t *ctr128_inc_big(uint8_t *counter) {
  uint64_t *data, c, n;
  data = (uint64_t *)counter;
  n = 16 / sizeof(uint64_t);
  do {
    --n;
    c = data[n];
    ++c;
    data[n] = c;
    if (c)
      return counter;
  } while (n);

  return counter;
}

void show_array(const char *explain, const uint8_t *array, size_t len) {
  printf("%20s ", explain);
  for(int i=0;i<len;i++) {
    printf("%02x ", array[i]);
  }
  printf("\n");
}

int main() {
  uint8_t a[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
  for(int i=0; i<257; i++) {
    char tmp[20];
    ctr128_inc(a);
    snprintf(tmp, 20, "ctr128_inc %d :", i+1);
    show_array(tmp, a, 16);
  }

  uint8_t b[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
  for(int i=0; i<257; i++) {
    char tmp[20];
    ctr128_inc_big(b);
    snprintf(tmp, 20, "ctr128_inc_big %d :", i+1);
    show_array(tmp, b, 16);
  }

  uint8_t c[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00};
  for(int i=0; i<257; i++) {
    char tmp[20];
    ctr128_inc(c);
    snprintf(tmp, 20, "overflow test %d :", i+1);
    show_array(tmp, c, 16);
  }

  return 0;
}