1/* $OpenBSD: e_chacha.c,v 1.14 2024/04/09 13:52:41 beck Exp $ */
2/*
3 * Copyright (c) 2014 Joel Sing <jsing@openbsd.org>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18#include <openssl/opensslconf.h>
19
20#ifndef OPENSSL_NO_CHACHA
21
22#include <openssl/chacha.h>
23#include <openssl/evp.h>
24#include <openssl/objects.h>
25
26#include "evp_local.h"
27
28static int
29chacha_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
30    const unsigned char *openssl_iv, int enc)
31{
32	if (key != NULL)
33		ChaCha_set_key((ChaCha_ctx *)ctx->cipher_data, key,
34		    EVP_CIPHER_CTX_key_length(ctx) * 8);
35	if (openssl_iv != NULL) {
36		const unsigned char *iv = openssl_iv + 8;
37		const unsigned char *counter = openssl_iv;
38
39		ChaCha_set_iv((ChaCha_ctx *)ctx->cipher_data, iv, counter);
40	}
41	return 1;
42}
43
44static int
45chacha_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in,
46    size_t len)
47{
48	ChaCha((ChaCha_ctx *)ctx->cipher_data, out, in, len);
49	return 1;
50}
51
52static const EVP_CIPHER chacha20_cipher = {
53	.nid = NID_chacha20,
54	.block_size = 1,
55	.key_len = 32,
56	/*
57	 * The 16-byte EVP IV is split into 4 little-endian 4-byte words
58	 *      evpiv[15:12]	evpiv[11:8]	evpiv[7:4]	evpiv[3:0]
59	 *	iv[1]		iv[0]		counter[1]	counter[0]
60	 * and passed as iv[] and counter[] to ChaCha_set_iv().
61	 */
62	.iv_len = 16,
63	.flags = EVP_CIPH_STREAM_CIPHER | EVP_CIPH_ALWAYS_CALL_INIT |
64	    EVP_CIPH_CUSTOM_IV,
65	.init = chacha_init,
66	.do_cipher = chacha_cipher,
67	.ctx_size = sizeof(ChaCha_ctx)
68};
69
70const EVP_CIPHER *
71EVP_chacha20(void)
72{
73	return (&chacha20_cipher);
74}
75LCRYPTO_ALIAS(EVP_chacha20);
76
77#endif
78