blob: 1b0083d871fb67eae7c3eb984906c05f0df09fec [file] [log] [blame]
Kyle Swenson7d38e032023-07-10 11:16:56 -06001/* SPDX-License-Identifier: GPL-2.0 OR MIT */
2/*
3 * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
4 */
5
6#ifndef _ZINC_CHACHA20_H
7#define _ZINC_CHACHA20_H
8
9#include <asm/unaligned.h>
10#include <linux/simd.h>
11#include <linux/kernel.h>
12#include <linux/types.h>
13
14enum chacha20_lengths {
15 CHACHA20_NONCE_SIZE = 16,
16 CHACHA20_KEY_SIZE = 32,
17 CHACHA20_KEY_WORDS = CHACHA20_KEY_SIZE / sizeof(u32),
18 CHACHA20_BLOCK_SIZE = 64,
19 CHACHA20_BLOCK_WORDS = CHACHA20_BLOCK_SIZE / sizeof(u32),
20 HCHACHA20_NONCE_SIZE = CHACHA20_NONCE_SIZE,
21 HCHACHA20_KEY_SIZE = CHACHA20_KEY_SIZE
22};
23
24enum chacha20_constants { /* expand 32-byte k */
25 CHACHA20_CONSTANT_EXPA = 0x61707865U,
26 CHACHA20_CONSTANT_ND_3 = 0x3320646eU,
27 CHACHA20_CONSTANT_2_BY = 0x79622d32U,
28 CHACHA20_CONSTANT_TE_K = 0x6b206574U
29};
30
31struct chacha20_ctx {
32 union {
33 u32 state[16];
34 struct {
35 u32 constant[4];
36 u32 key[8];
37 u32 counter[4];
38 };
39 };
40};
41
42static inline void chacha20_init(struct chacha20_ctx *ctx,
43 const u8 key[CHACHA20_KEY_SIZE],
44 const u64 nonce)
45{
46 ctx->constant[0] = CHACHA20_CONSTANT_EXPA;
47 ctx->constant[1] = CHACHA20_CONSTANT_ND_3;
48 ctx->constant[2] = CHACHA20_CONSTANT_2_BY;
49 ctx->constant[3] = CHACHA20_CONSTANT_TE_K;
50 ctx->key[0] = get_unaligned_le32(key + 0);
51 ctx->key[1] = get_unaligned_le32(key + 4);
52 ctx->key[2] = get_unaligned_le32(key + 8);
53 ctx->key[3] = get_unaligned_le32(key + 12);
54 ctx->key[4] = get_unaligned_le32(key + 16);
55 ctx->key[5] = get_unaligned_le32(key + 20);
56 ctx->key[6] = get_unaligned_le32(key + 24);
57 ctx->key[7] = get_unaligned_le32(key + 28);
58 ctx->counter[0] = 0;
59 ctx->counter[1] = 0;
60 ctx->counter[2] = nonce & U32_MAX;
61 ctx->counter[3] = nonce >> 32;
62}
63void chacha20(struct chacha20_ctx *ctx, u8 *dst, const u8 *src, u32 len,
64 simd_context_t *simd_context);
65
66void hchacha20(u32 derived_key[CHACHA20_KEY_WORDS],
67 const u8 nonce[HCHACHA20_NONCE_SIZE],
68 const u8 key[HCHACHA20_KEY_SIZE], simd_context_t *simd_context);
69
70#endif /* _ZINC_CHACHA20_H */