From 6a9c4d13fc97c0ad186e4d15839ef568659ebf6f Mon Sep 17 00:00:00 2001 From: jsing <> Date: Tue, 24 Jun 2014 18:12:09 +0000 Subject: If a chacha operation does not consume all of the generated key stream, ensure that we save it and consume it on subsequent writes. Otherwise we end up discarding part of the key stream and instead generate a new block at the start of the next write. This was only an issue for callers that did multiple writes that are not multiples of 64 bytes - in particular, the ChaCha20Poly1305 usage does not hit this problem since it performs encryption in a single-shot. For the same reason, this is also a non-issue when openssl(1) is used to encrypt with ChaCha. Issue identified by insane coder; reported to bugs@ by Joseph M. Schwartz. ok beck@ --- src/lib/libcrypto/chacha/chacha.c | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'src/lib/libcrypto/chacha/chacha.c') diff --git a/src/lib/libcrypto/chacha/chacha.c b/src/lib/libcrypto/chacha/chacha.c index a12c824fe6..141b3e99f6 100644 --- a/src/lib/libcrypto/chacha/chacha.c +++ b/src/lib/libcrypto/chacha/chacha.c @@ -1,4 +1,4 @@ -/* $OpenBSD: chacha.c,v 1.4 2014/06/12 15:49:28 deraadt Exp $ */ +/* $OpenBSD: chacha.c,v 1.5 2014/06/24 18:12:09 jsing Exp $ */ /* * Copyright (c) 2014 Joel Sing * @@ -22,6 +22,7 @@ void ChaCha_set_key(ChaCha_ctx *ctx, const unsigned char *key, uint32_t keybits) { chacha_keysetup((chacha_ctx *)ctx, key, keybits); + ctx->unused = 0; } void @@ -29,11 +30,25 @@ ChaCha_set_iv(ChaCha_ctx *ctx, const unsigned char *iv, const unsigned char *counter) { chacha_ivsetup((chacha_ctx *)ctx, iv, counter); + ctx->unused = 0; } void ChaCha(ChaCha_ctx *ctx, unsigned char *out, const unsigned char *in, size_t len) { + unsigned char *k; + int i, l; + + /* Consume remaining keystream, if any exists. */ + if (ctx->unused > 0) { + k = ctx->ks + 64 - ctx->unused; + l = (len > ctx->unused) ? ctx->unused : len; + for (i = 0; i < l; i++) + *(out++) = *(in++) ^ *(k++); + ctx->unused -= l; + len -= l; + } + chacha_encrypt_bytes((chacha_ctx *)ctx, in, out, (uint32_t)len); } -- cgit v1.2.3-55-g6feb