word.h 2.25 KB
Newer Older
Martin Schläffer committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
#ifndef WORD_H_
#define WORD_H_

#include <stdint.h>

#include "config.h"
#include "random.h"

typedef uint64_t share_t;

typedef struct {
  share_t s0;
  share_t s1;
  share_t s2;
} word_t;

__forceinline word_t WORD_T(uint64_t x) { return (word_t){x, 0, 0}; }

__forceinline uint64_t UINT64_T(word_t w) { return w.s0; }

__forceinline word_t TOSHARES(share_t in) {
  uint64_t r0 = rand64();
  uint64_t r1 = rand64();
  return (word_t){in ^ r0 ^ r1, r0, r1};
}

__forceinline share_t FROMSHARES(word_t in) { return in.s0 ^ in.s1 ^ in.s2; }

__forceinline word_t U64TOWORD(uint64_t x) {
#if ASCON_MASK_LOADS
  return TOSHARES(x);
#else
  return WORD_T(x);
#endif
}

__forceinline uint64_t WORDTOU64(word_t w) { return FROMSHARES(w); }

#define XOR(a, b)   \
  do {              \
    word_t t = b;   \
    (a).s0 ^= t.s0; \
    (a).s1 ^= t.s1; \
    (a).s2 ^= t.s2; \
  } while (0)

#define AND(a, b)                                                 \
  do {                                                            \
    word_t ta = a;                                                \
    word_t tb = b;                                                \
    (a).s0 = (ta.s0 & tb.s0) ^ (ta.s0 & tb.s1) ^ (ta.s0 & tb.s2); \
    (a).s1 = (ta.s1 & tb.s0) ^ (ta.s1 & tb.s1) ^ (ta.s1 & tb.s2); \
    (a).s2 = (ta.s2 & tb.s0) ^ (ta.s2 & tb.s1) ^ (ta.s2 & tb.s2); \
  } while (0)

__forceinline uint64_t ROR64(uint64_t x, int n) {
  return x >> n | x << (64 - n);
}

__forceinline word_t KEYROT(word_t lo2hi, word_t hi2lo) {
  word_t r;
  r.s0 = lo2hi.s0 << 32 | hi2lo.s0 >> 32;
  r.s1 = lo2hi.s1 << 32 | hi2lo.s1 >> 32;
  r.s2 = lo2hi.s2 << 32 | hi2lo.s2 >> 32;
  return r;
}

__forceinline int NOTZERO(word_t a, word_t b) {
  int result = 0;
  for (int i = 0; i < 8; ++i)
    result |= ((uint8_t*)&(a.s0))[i] ^ ((uint8_t*)&(a.s1))[i] ^
              ((uint8_t*)&(a.s2))[i];
  for (int i = 0; i < 8; ++i)
    result |= ((uint8_t*)&(b.s0))[i] ^ ((uint8_t*)&(b.s1))[i] ^
              ((uint8_t*)&(b.s2))[i];
  return result;
}

/* set padding byte in 64-bit Ascon word */
__forceinline word_t PAD(int i) { return WORD_T(0x80ull << (56 - 8 * i)); }

/* byte mask for 64-bit Ascon word (1 <= n <= 8) */
__forceinline word_t XMASK(int n) {
  return WORD_T(0x00ffffffffffffffull >> (n * 8 - 8));
}

#endif /* WORD_H_ */