1 // SPDX-License-Identifier: BSD-2-Clause
2 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 *
4 * LibTomCrypt is a library that provides various cryptographic
5 * algorithms in a highly modular and flexible manner.
6 *
7 * The library is free for all purposes without any express
8 * guarantee it works.
9 */
10
11 #include "tomcrypt_private.h"
12
13 #ifdef LTC_CHACHA20POLY1305_MODE
14
15 /**
16 Set IV + counter data to the ChaCha20Poly1305 state and reset the context
17 @param st The ChaCha20Poly1305 state
18 @param iv The IV data to add
19 @param ivlen The length of the IV (must be 12 or 8)
20 @return CRYPT_OK on success
21 */
chacha20poly1305_setiv(chacha20poly1305_state * st,const unsigned char * iv,unsigned long ivlen)22 int chacha20poly1305_setiv(chacha20poly1305_state *st, const unsigned char *iv, unsigned long ivlen)
23 {
24 chacha_state tmp_st;
25 int i, err;
26 unsigned char polykey[32];
27
28 LTC_ARGCHK(st != NULL);
29 LTC_ARGCHK(iv != NULL);
30 LTC_ARGCHK(ivlen == 12 || ivlen == 8);
31
32 /* set IV for chacha20 */
33 if (ivlen == 12) {
34 /* IV 96bit */
35 if ((err = chacha_ivctr32(&st->chacha, iv, ivlen, 1)) != CRYPT_OK) return err;
36 }
37 else {
38 /* IV 64bit */
39 if ((err = chacha_ivctr64(&st->chacha, iv, ivlen, 1)) != CRYPT_OK) return err;
40 }
41
42 /* copy chacha20 key to temporary state */
43 for(i = 0; i < 12; i++) tmp_st.input[i] = st->chacha.input[i];
44 tmp_st.rounds = 20;
45 /* set IV */
46 if (ivlen == 12) {
47 /* IV 32bit */
48 if ((err = chacha_ivctr32(&tmp_st, iv, ivlen, 0)) != CRYPT_OK) return err;
49 }
50 else {
51 /* IV 64bit */
52 if ((err = chacha_ivctr64(&tmp_st, iv, ivlen, 0)) != CRYPT_OK) return err;
53 }
54 /* (re)generate new poly1305 key */
55 if ((err = chacha_keystream(&tmp_st, polykey, 32)) != CRYPT_OK) return err;
56 /* (re)initialise poly1305 */
57 if ((err = poly1305_init(&st->poly, polykey, 32)) != CRYPT_OK) return err;
58 st->ctlen = 0;
59 st->aadlen = 0;
60 st->aadflg = 1;
61
62 return CRYPT_OK;
63 }
64
65 #endif
66
67 /* ref: $Format:%D$ */
68 /* git commit: $Format:%H$ */
69 /* commit time: $Format:%ai$ */
70