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