1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt_private.h"
5 
6 #ifdef LTC_CHACHA20POLY1305_MODE
7 
8 /**
9   Terminate a ChaCha20Poly1305 stream
10   @param st      The ChaCha20Poly1305 state
11   @param tag     [out] The destination for the MAC tag
12   @param taglen  [in/out]  The length of the MAC tag
13   @return CRYPT_OK on success
14  */
chacha20poly1305_done(chacha20poly1305_state * st,unsigned char * tag,unsigned long * taglen)15 int chacha20poly1305_done(chacha20poly1305_state *st, unsigned char *tag, unsigned long *taglen)
16 {
17    unsigned char padzero[16] = { 0 };
18    unsigned long padlen;
19    unsigned char buf[16];
20    int err;
21 
22    LTC_ARGCHK(st != NULL);
23 
24    padlen = 16 - (unsigned long)(st->ctlen % 16);
25    if (padlen < 16) {
26      if ((err = poly1305_process(&st->poly, padzero, padlen)) != CRYPT_OK) return err;
27    }
28    STORE64L(st->aadlen, buf);
29    STORE64L(st->ctlen, buf + 8);
30    if ((err = poly1305_process(&st->poly, buf, 16)) != CRYPT_OK)           return err;
31    if ((err = poly1305_done(&st->poly, tag, taglen)) != CRYPT_OK)          return err;
32    if ((err = chacha_done(&st->chacha)) != CRYPT_OK)                       return err;
33    return CRYPT_OK;
34 }
35 
36 #endif
37