1 /*
2 * Copyright 2014-2022 The GmSSL Project. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the License); you may
5 * not use this file except in compliance with the License.
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 */
9
10
11
12 #include <stdio.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #include <gmssl/chacha20.h>
16 #include <gmssl/endian.h>
17
18
chacha20_init(CHACHA20_STATE * state,const uint8_t key[CHACHA20_KEY_SIZE],const uint8_t nonce[CHACHA20_NONCE_SIZE],uint32_t counter)19 void chacha20_init(CHACHA20_STATE *state,
20 const uint8_t key[CHACHA20_KEY_SIZE],
21 const uint8_t nonce[CHACHA20_NONCE_SIZE],
22 uint32_t counter)
23 {
24 state->d[ 0] = 0x61707865;
25 state->d[ 1] = 0x3320646e;
26 state->d[ 2] = 0x79622d32;
27 state->d[ 3] = 0x6b206574;
28 state->d[ 4] = GETU32_LE(key );
29 state->d[ 5] = GETU32_LE(key + 4);
30 state->d[ 6] = GETU32_LE(key + 8);
31 state->d[ 7] = GETU32_LE(key + 12);
32 state->d[ 8] = GETU32_LE(key + 16);
33 state->d[ 9] = GETU32_LE(key + 20);
34 state->d[10] = GETU32_LE(key + 24);
35 state->d[11] = GETU32_LE(key + 28);
36 state->d[12] = counter;
37 state->d[13] = GETU32_LE(nonce);
38 state->d[14] = GETU32_LE(nonce + 4);
39 state->d[15] = GETU32_LE(nonce + 8);
40 }
41
42 /* quarter round */
43 #define QR(A, B, C, D) \
44 A += B; D ^= A; D = ROL32(D, 16); \
45 C += D; B ^= C; B = ROL32(B, 12); \
46 A += B; D ^= A; D = ROL32(D, 8); \
47 C += D; B ^= C; B = ROL32(B, 7)
48
49 /* double round on state 4x4 matrix:
50 * four column rounds and and four diagonal rounds
51 *
52 * 0 1 2 3
53 * 4 5 6 7
54 * 8 9 10 11
55 * 12 13 14 15
56 *
57 */
58 #define DR(S) \
59 QR(S[0], S[4], S[ 8], S[12]); \
60 QR(S[1], S[5], S[ 9], S[13]); \
61 QR(S[2], S[6], S[10], S[14]); \
62 QR(S[3], S[7], S[11], S[15]); \
63 QR(S[0], S[5], S[10], S[15]); \
64 QR(S[1], S[6], S[11], S[12]); \
65 QR(S[2], S[7], S[ 8], S[13]); \
66 QR(S[3], S[4], S[ 9], S[14])
67
chacha20_generate_keystream(CHACHA20_STATE * state,size_t counts,uint8_t * out)68 void chacha20_generate_keystream(CHACHA20_STATE *state, size_t counts, uint8_t *out)
69 {
70 uint32_t working_state[16];
71 int i;
72
73 while (counts-- > 0) {
74 memcpy(working_state, state->d, sizeof(working_state));
75 for (i = 0; i < 10; i++) {
76 DR(working_state);
77 }
78 for (i = 0; i < 16; i++) {
79 working_state[i] += state->d[i];
80 PUTU32_LE(out, working_state[i]);
81 out += sizeof(uint32_t);
82 }
83 state->d[12]++;
84 }
85 }
86