1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt_private.h"
5 
6 #ifdef LTC_CHACHA
7 
8 /**
9    Encrypt (or decrypt) bytes of ciphertext (or plaintext) with ChaCha
10    @param key     The key
11    @param keylen  The key length
12    @param iv      The initial vector
13    @param ivlen   The initial vector length
14    @param datain  The plaintext (or ciphertext)
15    @param datalen The length of the input and output (octets)
16    @param rounds  The number of rounds
17    @param dataout [out] The ciphertext (or plaintext)
18    @return CRYPT_OK if successful
19 */
chacha_memory(const unsigned char * key,unsigned long keylen,unsigned long rounds,const unsigned char * iv,unsigned long ivlen,ulong64 counter,const unsigned char * datain,unsigned long datalen,unsigned char * dataout)20 int chacha_memory(const unsigned char *key,    unsigned long keylen,  unsigned long rounds,
21                   const unsigned char *iv,     unsigned long ivlen,   ulong64 counter,
22                   const unsigned char *datain, unsigned long datalen, unsigned char *dataout)
23 {
24    chacha_state st;
25    int err;
26 
27    LTC_ARGCHK(ivlen <= 8 || counter < 4294967296);       /* 2**32 */
28 
29    if ((err = chacha_setup(&st, key, keylen, rounds))       != CRYPT_OK) goto WIPE_KEY;
30    if (ivlen > 8) {
31         if ((err = chacha_ivctr32(&st, iv, ivlen, (ulong32)counter)) != CRYPT_OK) goto WIPE_KEY;
32    } else {
33         if ((err = chacha_ivctr64(&st, iv, ivlen, counter)) != CRYPT_OK) goto WIPE_KEY;
34    }
35    err = chacha_crypt(&st, datain, datalen, dataout);
36 WIPE_KEY:
37    chacha_done(&st);
38    return err;
39 }
40 
41 #endif /* LTC_CHACHA */
42