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    Encrypt bytes of ciphertext with ChaCha20Poly1305
10    @param st      The ChaCha20Poly1305 state
11    @param in      The plaintext
12    @param inlen   The length of the input (octets)
13    @param out     [out] The ciphertext (length inlen)
14    @return CRYPT_OK if successful
15 */
chacha20poly1305_encrypt(chacha20poly1305_state * st,const unsigned char * in,unsigned long inlen,unsigned char * out)16 int chacha20poly1305_encrypt(chacha20poly1305_state *st, const unsigned char *in, unsigned long inlen, unsigned char *out)
17 {
18    unsigned char padzero[16] = { 0 };
19    unsigned long padlen;
20    int err;
21 
22    LTC_ARGCHK(st != NULL);
23 
24    if ((err = chacha_crypt(&st->chacha, in, inlen, out)) != CRYPT_OK)         return err;
25    if (st->aadflg) {
26       padlen = 16 - (unsigned long)(st->aadlen % 16);
27       if (padlen < 16) {
28         if ((err = poly1305_process(&st->poly, padzero, padlen)) != CRYPT_OK) return err;
29       }
30       st->aadflg = 0; /* no more AAD */
31    }
32    if ((err = poly1305_process(&st->poly, out, inlen)) != CRYPT_OK)           return err;
33    st->ctlen += (ulong64)inlen;
34    return CRYPT_OK;
35 }
36 
37 #endif
38