2 * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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 /* Adapted from the public domain code by D. Bernstein from SUPERCOP. */
14 #include "internal/chacha.h"
16 typedef unsigned int u32;
17 typedef unsigned char u8;
23 # define ROTATE(v, n) (((v) << (n)) | ((v) >> (32 - (n))))
25 # define U32TO8_LITTLE(p, v) do { \
26 (p)[0] = (u8)(v >> 0); \
27 (p)[1] = (u8)(v >> 8); \
28 (p)[2] = (u8)(v >> 16); \
29 (p)[3] = (u8)(v >> 24); \
32 /* QUARTERROUND updates a, b, c, d with a ChaCha "quarter" round. */
33 # define QUARTERROUND(a,b,c,d) ( \
34 x[a] += x[b], x[d] = ROTATE((x[d] ^ x[a]),16), \
35 x[c] += x[d], x[b] = ROTATE((x[b] ^ x[c]),12), \
36 x[a] += x[b], x[d] = ROTATE((x[d] ^ x[a]), 8), \
37 x[c] += x[d], x[b] = ROTATE((x[b] ^ x[c]), 7) )
39 /* chacha_core performs 20 rounds of ChaCha on the input words in
40 * |input| and writes the 64 output bytes to |output|. */
41 static void chacha20_core(chacha_buf *output, const u32 input[16])
50 memcpy(x, input, sizeof(x));
52 for (i = 20; i > 0; i -= 2) {
53 QUARTERROUND(0, 4, 8, 12);
54 QUARTERROUND(1, 5, 9, 13);
55 QUARTERROUND(2, 6, 10, 14);
56 QUARTERROUND(3, 7, 11, 15);
57 QUARTERROUND(0, 5, 10, 15);
58 QUARTERROUND(1, 6, 11, 12);
59 QUARTERROUND(2, 7, 8, 13);
60 QUARTERROUND(3, 4, 9, 14);
63 if (is_endian.little) {
64 for (i = 0; i < 16; ++i)
65 output->u[i] = x[i] + input[i];
67 for (i = 0; i < 16; ++i)
68 U32TO8_LITTLE(output->c + 4 * i, (x[i] + input[i]));
72 void ChaCha20_ctr32(unsigned char *out, const unsigned char *inp,
73 size_t len, const unsigned int key[8],
74 const unsigned int counter[4])
80 /* sigma constant "expand 32-byte k" in little-endian encoding */
81 input[0] = ((u32)'e') | ((u32)'x'<<8) | ((u32)'p'<<16) | ((u32)'a'<<24);
82 input[1] = ((u32)'n') | ((u32)'d'<<8) | ((u32)' '<<16) | ((u32)'3'<<24);
83 input[2] = ((u32)'2') | ((u32)'-'<<8) | ((u32)'b'<<16) | ((u32)'y'<<24);
84 input[3] = ((u32)'t') | ((u32)'e'<<8) | ((u32)' '<<16) | ((u32)'k'<<24);
95 input[12] = counter[0];
96 input[13] = counter[1];
97 input[14] = counter[2];
98 input[15] = counter[3];
105 chacha20_core(&buf, input);
107 for (i = 0; i < todo; i++)
108 out[i] = inp[i] ^ buf.c[i];
114 * Advance 32-bit counter. Note that as subroutine is so to
115 * say nonce-agnostic, this limited counter width doesn't
116 * prevent caller from implementing wider counter. It would
117 * simply take two calls split on counter overflow...