hash.c 2.03 KB
Newer Older
Martin Schläffer committed
1 2
#include "api.h"
#include "ascon.h"
Enrico Pozzobon committed
3
#include "crypto_hash.h"
Martin Schläffer committed
4 5 6
#include "permutations.h"
#include "printstate.h"

Enrico Pozzobon committed
7 8 9
#if !ASCON_INLINE_MODE
#undef forceinline
#define forceinline
Martin Schläffer committed
10
#endif
Enrico Pozzobon committed
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

forceinline void ascon_hashinit(state_t* s) {
  /* initialize */
#if ASCON_HASH_OUTLEN == 32 && ASCON_HASH_ROUNDS == 12
  s->x0 = ASCON_HASH_IV0;
  s->x1 = ASCON_HASH_IV1;
  s->x2 = ASCON_HASH_IV2;
  s->x3 = ASCON_HASH_IV3;
  s->x4 = ASCON_HASH_IV4;
#elif ASCON_HASH_OUTLEN == 32 && ASCON_HASH_ROUNDS == 8
  s->x0 = ASCON_HASHA_IV0;
  s->x1 = ASCON_HASHA_IV1;
  s->x2 = ASCON_HASHA_IV2;
  s->x3 = ASCON_HASHA_IV3;
  s->x4 = ASCON_HASHA_IV4;
#elif ASCON_HASH_OUTLEN == 0 && ASCON_HASH_ROUNDS == 12
  s->x0 = ASCON_XOF_IV0;
  s->x1 = ASCON_XOF_IV1;
  s->x2 = ASCON_XOF_IV2;
  s->x3 = ASCON_XOF_IV3;
  s->x4 = ASCON_XOF_IV4;
#elif ASCON_HASH_OUTLEN == 0 && ASCON_HASH_ROUNDS == 8
  s->x0 = ASCON_XOFA_IV0;
  s->x1 = ASCON_XOFA_IV1;
  s->x2 = ASCON_XOFA_IV2;
  s->x3 = ASCON_XOFA_IV3;
  s->x4 = ASCON_XOFA_IV4;
Martin Schläffer committed
38
#endif
Enrico Pozzobon committed
39 40
  printstate("initialization", s);
}
Martin Schläffer committed
41

Enrico Pozzobon committed
42 43 44 45 46 47 48
forceinline void ascon_absorb(state_t* s, const uint8_t* in, uint64_t inlen) {
  /* absorb full plaintext blocks */
  while (inlen >= ASCON_HASH_RATE) {
    s->x0 = XOR(s->x0, LOAD(in, 8));
    P(s, ASCON_HASH_ROUNDS);
    in += ASCON_HASH_RATE;
    inlen -= ASCON_HASH_RATE;
Martin Schläffer committed
49
  }
Enrico Pozzobon committed
50 51 52 53 54 55
  /* absorb final plaintext block */
  if (inlen) s->x0 = XOR(s->x0, LOAD(in, inlen));
  s->x0 = XOR(s->x0, PAD(inlen));
  P(s, 12);
  printstate("absorb plaintext", s);
}
Martin Schläffer committed
56

Enrico Pozzobon committed
57 58 59 60 61 62 63
forceinline void ascon_squeeze(state_t* s, uint8_t* out, uint64_t outlen) {
  /* squeeze full output blocks */
  while (outlen > ASCON_HASH_RATE) {
    STORE(out, s->x0, 8);
    P(s, ASCON_HASH_ROUNDS);
    out += ASCON_HASH_RATE;
    outlen -= ASCON_HASH_RATE;
Martin Schläffer committed
64
  }
Enrico Pozzobon committed
65 66 67 68
  /* squeeze final output block */
  STORE(out, s->x0, outlen);
  printstate("squeeze output", s);
}
Martin Schläffer committed
69

Enrico Pozzobon committed
70 71 72 73 74 75
int crypto_hash(unsigned char* out, const unsigned char* in,
                unsigned long long inlen) {
  state_t s;
  ascon_hashinit(&s);
  ascon_absorb(&s, in, inlen);
  ascon_squeeze(&s, out, CRYPTO_BYTES);
Martin Schläffer committed
76 77
  return 0;
}