encrypt.c 1.64 KB
Newer Older
lwc-tester committed
1
#include "api.h"
Martin Schläffer committed
2 3
#include "ascon.h"
#include "loadstore.h"
lwc-tester committed
4
#include "permutations.h"
Martin Schläffer committed
5
#include "printstate.h"
lwc-tester committed
6

Martin Schläffer committed
7 8 9 10 11 12
int crypto_aead_encrypt(uint8_t* c, uint64_t* clen, const uint8_t* m,
                        uint64_t mlen, const uint8_t* ad, uint64_t adlen,
                        const uint8_t* nsec, const uint8_t* npub,
                        const uint8_t* k) {
  uint64_t K0, K1, N0, N1;
  state_t s;
lwc-tester committed
13 14
  (void)nsec;

Martin Schläffer committed
15
  /* set ciphertext size */
lwc-tester committed
16 17
  *clen = mlen + CRYPTO_ABYTES;

Martin Schläffer committed
18 19 20 21 22 23 24 25
  /* load key and nonce */
  K0 = LOAD(k, 8);
  K1 = LOAD(k + 8, 8);
  N0 = LOAD(npub, 8);
  N1 = LOAD(npub + 8, 8);

  /* initialization */
  s.x0 = ASCON_128_IV;
lwc-tester committed
26 27 28 29 30 31 32
  s.x1 = K0;
  s.x2 = K1;
  s.x3 = N0;
  s.x4 = N1;
  P12(&s);
  s.x3 ^= K0;
  s.x4 ^= K1;
Martin Schläffer committed
33
  printstate("initialization", &s);
lwc-tester committed
34

Martin Schläffer committed
35
  /* process associated data */
lwc-tester committed
36
  if (adlen) {
Martin Schläffer committed
37 38
    while (adlen >= ASCON_128_RATE) {
      s.x0 ^= LOAD(ad, 8);
lwc-tester committed
39
      P6(&s);
Martin Schläffer committed
40 41
      ad += ASCON_128_RATE;
      adlen -= ASCON_128_RATE;
lwc-tester committed
42
    }
Martin Schläffer committed
43 44 45
    /* final associated data block */
    s.x0 ^= LOAD(ad, adlen);
    s.x0 ^= PAD(adlen);
lwc-tester committed
46 47 48
    P6(&s);
  }
  s.x4 ^= 1;
Martin Schläffer committed
49
  printstate("process associated data", &s);
lwc-tester committed
50

Martin Schläffer committed
51 52 53 54
  /* process plaintext */
  while (mlen >= ASCON_128_RATE) {
    s.x0 ^= LOAD(m, 8);
    STORE(c, s.x0, 8);
lwc-tester committed
55
    P6(&s);
Martin Schläffer committed
56 57 58
    m += ASCON_128_RATE;
    c += ASCON_128_RATE;
    mlen -= ASCON_128_RATE;
lwc-tester committed
59
  }
Martin Schläffer committed
60 61 62 63
  /* final plaintext block */
  s.x0 ^= LOAD(m, mlen);
  STORE(c, s.x0, mlen);
  s.x0 ^= PAD(mlen);
lwc-tester committed
64
  c += mlen;
Martin Schläffer committed
65
  printstate("process plaintext", &s);
lwc-tester committed
66

Martin Schläffer committed
67
  /* finalization */
lwc-tester committed
68 69 70 71 72
  s.x1 ^= K0;
  s.x2 ^= K1;
  P12(&s);
  s.x3 ^= K0;
  s.x4 ^= K1;
Martin Schläffer committed
73
  printstate("finalization", &s);
lwc-tester committed
74

Martin Schläffer committed
75 76 77
  /* set tag */
  STORE(c, s.x3, 8);
  STORE(c + 8, s.x4, 8);
lwc-tester committed
78 79 80

  return 0;
}