Leancrypto 1.6.0
Post-Quantum Cryptographic Library
Loading...
Searching...
No Matches
lc_chacha20_private.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 2022 - 2025, Stephan Mueller <smueller@chronox.de>
3 *
4 * License: see LICENSE file in root directory
5 *
6 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
7 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
8 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
9 * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
10 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
11 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
12 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
13 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
14 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
15 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
16 * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
17 * DAMAGE.
18 */
19
20#ifndef LC_CHACHA20_PRIVATE_H
21#define LC_CHACHA20_PRIVATE_H
22
23#include "ext_headers.h"
24
25#ifdef __cplusplus
26extern "C" {
27#endif
28
30#define LC_CC20_KEY_SIZE 32
31#define LC_CC20_KEY_SIZE_WORDS (LC_CC20_KEY_SIZE / sizeof(uint32_t))
32
33#define LC_CC20_BLOCK_SIZE ((4 + 8 + 4) * sizeof(uint32_t))
34#define LC_CC20_BLOCK_SIZE_WORDS (LC_CC20_BLOCK_SIZE / sizeof(uint32_t))
35
36/*
37 * State according to RFC 7539 section 2.3
38 *
39 * For accelerated ChaCha20 implementatinos, the key and the counter must be
40 * aligned to 16 bytes boundary. This is guaranteed when aligning the entire
41 * structure to 16 bytes as the constant field is 16 bytes in size.
42 */
43struct lc_sym_state {
44 uint32_t constants[4];
45 union {
46 uint32_t u[LC_CC20_KEY_SIZE_WORDS];
47 uint8_t b[LC_CC20_KEY_SIZE];
48 } key;
49 uint32_t counter[4];
50 union {
51 uint32_t u[LC_CC20_BLOCK_SIZE_WORDS];
52 uint8_t b[LC_CC20_BLOCK_SIZE];
53 } keystream;
54 uint8_t keystream_ptr;
55};
56
57#define LC_CC20_STATE_SIZE (sizeof(struct lc_sym_state))
58
59static inline void cc20_init_constants(struct lc_sym_state *ctx)
60{
61 if (!ctx)
62 return;
63
64 /* String "expand 32-byte k" */
65 ctx->constants[0] = 0x61707865;
66 ctx->constants[1] = 0x3320646e;
67 ctx->constants[2] = 0x79622d32;
68 ctx->constants[3] = 0x6b206574;
69}
70
71static inline void cc20_counter_overflow(struct lc_sym_state *ctx)
72{
73 if (ctx->counter[0] == 0) {
74 ctx->counter[1]++;
75 if (ctx->counter[1] == 0) {
76 ctx->counter[2]++;
77 if (ctx->counter[2] == 0)
78 ctx->counter[3]++;
79 }
80 }
81}
82
83static inline void cc20_inc_counter(struct lc_sym_state *ctx)
84{
85 ctx->counter[0]++;
86 cc20_counter_overflow(ctx);
87}
88
90
91#ifdef __cplusplus
92}
93#endif
94
95#endif /* LC_CHACHA20_PRIVATE_H */