2 * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* chacha20 cipher implementation */
12 #include "cipher_chacha20.h"
14 static int chacha20_initkey(PROV_CIPHER_CTX *bctx, const uint8_t *key,
17 PROV_CHACHA20_CTX *ctx = (PROV_CHACHA20_CTX *)bctx;
21 for (i = 0; i < CHACHA_KEY_SIZE; i += 4)
22 ctx->key.d[i / 4] = CHACHA_U8TOU32(key + i);
28 static int chacha20_initiv(PROV_CIPHER_CTX *bctx)
30 PROV_CHACHA20_CTX *ctx = (PROV_CHACHA20_CTX *)bctx;
34 for (i = 0; i < CHACHA_CTR_SIZE; i += 4)
35 ctx->counter[i / 4] = CHACHA_U8TOU32(bctx->oiv + i);
40 static int chacha20_cipher(PROV_CIPHER_CTX *bctx, unsigned char *out,
41 const unsigned char *in, size_t inl)
43 PROV_CHACHA20_CTX *ctx = (PROV_CHACHA20_CTX *)bctx;
44 unsigned int n, rem, ctr32;
48 while (inl > 0 && n < CHACHA_BLK_SIZE) {
49 *out++ = *in++ ^ ctx->buf[n++];
57 if (n == CHACHA_BLK_SIZE) {
60 if (ctx->counter[0] == 0)
65 rem = (unsigned int)(inl % CHACHA_BLK_SIZE);
67 ctr32 = ctx->counter[0];
68 while (inl >= CHACHA_BLK_SIZE) {
69 size_t blocks = inl / CHACHA_BLK_SIZE;
72 * 1<<28 is just a not-so-small yet not-so-large number...
73 * Below condition is practically never met, but it has to
74 * be checked for code correctness.
76 if (sizeof(size_t) > sizeof(unsigned int) && blocks > (1U << 28))
80 * As ChaCha20_ctr32 operates on 32-bit counter, caller
81 * has to handle overflow. 'if' below detects the
82 * overflow, which is then handled by limiting the
83 * amount of blocks to the exact overflow point...
85 ctr32 += (unsigned int)blocks;
90 blocks *= CHACHA_BLK_SIZE;
91 ChaCha20_ctr32(out, in, blocks, ctx->key.d, ctx->counter);
96 ctx->counter[0] = ctr32;
97 if (ctr32 == 0) ctx->counter[1]++;
101 memset(ctx->buf, 0, sizeof(ctx->buf));
102 ChaCha20_ctr32(ctx->buf, ctx->buf, CHACHA_BLK_SIZE,
103 ctx->key.d, ctx->counter);
104 for (n = 0; n < rem; n++)
105 out[n] = in[n] ^ ctx->buf[n];
106 ctx->partial_len = rem;
112 static const PROV_CIPHER_HW_CHACHA20 chacha20_hw = {
113 { chacha20_initkey, chacha20_cipher },
117 const PROV_CIPHER_HW *PROV_CIPHER_HW_chacha20(size_t keybits)
119 return (PROV_CIPHER_HW *)&chacha20_hw;