e_chacha.c revision 1.7
1/* $OpenBSD: e_chacha.c,v 1.7 2020/01/26 07:34:05 tb 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_locl.h"
27
28static int chacha_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
29    const unsigned char *in, size_t len);
30static int chacha_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
31    const unsigned char *iv, int enc);
32
33static const EVP_CIPHER chacha20_cipher = {
34	.nid = NID_chacha20,
35	.block_size = 1,
36	.key_len = 32,
37	/*
38	 * The 128 bit EVP IV is split for ChaCha into four 32 bit pieces:
39	 * 			counter[0]	counter[1]	iv[0]	iv[1]
40	 * OpenSSL exposes these as;
41	 * 	openssl_iv =	counter[0]	iv[0]		iv[1]	iv[2]
42	 * Due to the cipher internal state's symmetry, these are functionally
43	 * equivalent.
44	 */
45	.iv_len = 16,
46	.flags = EVP_CIPH_STREAM_CIPHER | EVP_CIPH_ALWAYS_CALL_INIT |
47	    EVP_CIPH_CUSTOM_IV,
48	.init = chacha_init,
49	.do_cipher = chacha_cipher,
50	.ctx_size = sizeof(ChaCha_ctx)
51};
52
53const EVP_CIPHER *
54EVP_chacha20(void)
55{
56	return (&chacha20_cipher);
57}
58
59static int
60chacha_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
61    const unsigned char *openssl_iv, int enc)
62{
63	if (key != NULL)
64		ChaCha_set_key((ChaCha_ctx *)ctx->cipher_data, key,
65		    EVP_CIPHER_CTX_key_length(ctx) * 8);
66	if (openssl_iv != NULL) {
67		const unsigned char *iv = openssl_iv + 8;
68		const unsigned char *counter = openssl_iv;
69
70		ChaCha_set_iv((ChaCha_ctx *)ctx->cipher_data, iv, counter);
71	}
72	return 1;
73}
74
75static int
76chacha_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in,
77    size_t len)
78{
79	ChaCha((ChaCha_ctx *)ctx->cipher_data, out, in, len);
80	return 1;
81}
82
83#endif
84