e_chacha.c revision 1.6
1/* $OpenBSD: e_chacha.c,v 1.6 2020/01/26 02:39:58 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	.iv_len = 16, /* OpenSSL has 8 byte counter followed by 8 byte iv */
38	.flags = EVP_CIPH_STREAM_CIPHER | EVP_CIPH_ALWAYS_CALL_INIT |
39	    EVP_CIPH_CUSTOM_IV,
40	.init = chacha_init,
41	.do_cipher = chacha_cipher,
42	.ctx_size = sizeof(ChaCha_ctx)
43};
44
45const EVP_CIPHER *
46EVP_chacha20(void)
47{
48	return (&chacha20_cipher);
49}
50
51static int
52chacha_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
53    const unsigned char *iv, int enc)
54{
55	if (key != NULL)
56		ChaCha_set_key((ChaCha_ctx *)ctx->cipher_data, key,
57		    EVP_CIPHER_CTX_key_length(ctx) * 8);
58	if (iv != NULL) {
59		const unsigned char *openssl_iv = iv + 8;
60		const unsigned char *counter = iv;
61
62		ChaCha_set_iv((ChaCha_ctx *)ctx->cipher_data, openssl_iv,
63		    counter);
64	}
65	return 1;
66}
67
68static int
69chacha_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in,
70    size_t len)
71{
72	ChaCha((ChaCha_ctx *)ctx->cipher_data, out, in, len);
73	return 1;
74}
75
76#endif
77