1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 /* The implementation is based on:
5  * chacha-ref.c version 20080118
6  * Public domain from D. J. Bernstein
7  */
8 
9 #include "tomcrypt_private.h"
10 
11 #ifdef LTC_CHACHA
12 
13 static const char * const sigma = "expand 32-byte k";
14 static const char * const tau   = "expand 16-byte k";
15 
16 /**
17    Initialize an ChaCha context (only the key)
18    @param st        [out] The destination of the ChaCha state
19    @param key       The secret key
20    @param keylen    The length of the secret key (octets)
21    @param rounds    Number of rounds (e.g. 20 for ChaCha20)
22    @return CRYPT_OK if successful
23 */
chacha_setup(chacha_state * st,const unsigned char * key,unsigned long keylen,int rounds)24 int chacha_setup(chacha_state *st, const unsigned char *key, unsigned long keylen, int rounds)
25 {
26    const char *constants;
27 
28    LTC_ARGCHK(st  != NULL);
29    LTC_ARGCHK(key != NULL);
30    LTC_ARGCHK(keylen == 32 || keylen == 16);
31 
32    if (rounds == 0) rounds = 20;
33 
34    LOAD32L(st->input[4], key + 0);
35    LOAD32L(st->input[5], key + 4);
36    LOAD32L(st->input[6], key + 8);
37    LOAD32L(st->input[7], key + 12);
38    if (keylen == 32) { /* 256bit */
39       key += 16;
40       constants = sigma;
41    } else { /* 128bit */
42       constants = tau;
43    }
44    LOAD32L(st->input[8],  key + 0);
45    LOAD32L(st->input[9],  key + 4);
46    LOAD32L(st->input[10], key + 8);
47    LOAD32L(st->input[11], key + 12);
48    LOAD32L(st->input[0],  constants + 0);
49    LOAD32L(st->input[1],  constants + 4);
50    LOAD32L(st->input[2],  constants + 8);
51    LOAD32L(st->input[3],  constants + 12);
52    st->rounds = rounds; /* e.g. 20 for chacha20 */
53    st->ivlen = 0; /* will be set later by chacha_ivctr(32|64) */
54    return CRYPT_OK;
55 }
56 
57 #endif
58