#include <openssl/chacha.h>
#include <assert.h>
#include <string.h>
#include "../internal.h"
#include "internal.h"
static const uint8_t sigma[16] = …;
#define QUARTERROUND(a, b, c, d) …
void CRYPTO_hchacha20(uint8_t out[32], const uint8_t key[32],
const uint8_t nonce[16]) { … }
#if defined(CHACHA20_ASM_NOHW)
static void ChaCha20_ctr32(uint8_t *out, const uint8_t *in, size_t in_len,
const uint32_t key[8], const uint32_t counter[4]) { … }
#endif
#if defined(CHACHA20_ASM_NOHW)
void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, size_t in_len,
const uint8_t key[32], const uint8_t nonce[12],
uint32_t counter) { … }
#else
static void chacha_core(uint8_t output[64], const uint32_t input[16]) {
uint32_t x[16];
int i;
OPENSSL_memcpy(x, input, sizeof(uint32_t) * 16);
for (i = 20; i > 0; i -= 2) {
QUARTERROUND(0, 4, 8, 12)
QUARTERROUND(1, 5, 9, 13)
QUARTERROUND(2, 6, 10, 14)
QUARTERROUND(3, 7, 11, 15)
QUARTERROUND(0, 5, 10, 15)
QUARTERROUND(1, 6, 11, 12)
QUARTERROUND(2, 7, 8, 13)
QUARTERROUND(3, 4, 9, 14)
}
for (i = 0; i < 16; ++i) {
x[i] += input[i];
}
for (i = 0; i < 16; ++i) {
CRYPTO_store_u32_le(output + 4 * i, x[i]);
}
}
void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, size_t in_len,
const uint8_t key[32], const uint8_t nonce[12],
uint32_t counter) {
assert(!buffers_alias(out, in_len, in, in_len) || in == out);
uint32_t input[16];
uint8_t buf[64];
size_t todo, i;
input[0] = CRYPTO_load_u32_le(sigma + 0);
input[1] = CRYPTO_load_u32_le(sigma + 4);
input[2] = CRYPTO_load_u32_le(sigma + 8);
input[3] = CRYPTO_load_u32_le(sigma + 12);
input[4] = CRYPTO_load_u32_le(key + 0);
input[5] = CRYPTO_load_u32_le(key + 4);
input[6] = CRYPTO_load_u32_le(key + 8);
input[7] = CRYPTO_load_u32_le(key + 12);
input[8] = CRYPTO_load_u32_le(key + 16);
input[9] = CRYPTO_load_u32_le(key + 20);
input[10] = CRYPTO_load_u32_le(key + 24);
input[11] = CRYPTO_load_u32_le(key + 28);
input[12] = counter;
input[13] = CRYPTO_load_u32_le(nonce + 0);
input[14] = CRYPTO_load_u32_le(nonce + 4);
input[15] = CRYPTO_load_u32_le(nonce + 8);
while (in_len > 0) {
todo = sizeof(buf);
if (in_len < todo) {
todo = in_len;
}
chacha_core(buf, input);
for (i = 0; i < todo; i++) {
out[i] = in[i] ^ buf[i];
}
out += todo;
in += todo;
in_len -= todo;
input[12]++;
}
}
#endif