From 06f835e27c4000d9edea6e0e517c23c5a764dc6f Mon Sep 17 00:00:00 2001 From: Lucas Gabriel Vuotto Date: Fri, 7 Jun 2024 00:29:25 +0000 Subject: [PATCH] cipher/chacha20: treat the counter as part of the nonce --- cipher_chacha20.c | 12 ++++++------ impl_chacha20.c | 8 ++++---- impl_chacha20.h | 3 +-- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/cipher_chacha20.c b/cipher_chacha20.c index 13b94ec..cd4ca40 100644 --- a/cipher_chacha20.c +++ b/cipher_chacha20.c @@ -39,9 +39,9 @@ chacha20_common_init_from(void *arg, const uint8_t *key, size_t keylen, ctx->s[i] = 0; for (i = 0; i < CHACHA20_KEY_WORDS; i++) ctx->k[i] = load32le(&key[i * 4]); - ctx->c = counter; - for (i = 0; i < CHACHA20_NONCE_WORDS; i++) - ctx->n[i] = load32le(&iv[i * 4]); + ctx->n[0] = counter; + for (i = 1; i < CHACHA20_NONCE_WORDS; i++) + ctx->n[i] = load32le(&iv[(i - 1) * 4]); ctx->mlen = 0; return 1; @@ -66,7 +66,7 @@ chacha20_common_update(void *arg, uint8_t *out, size_t *outlen, if (inlen > SIZE_MAX - (CHACHA20_CHUNK - 1) - ctx->mlen) return 0; blocks = (inlen + ctx->mlen + CHACHA20_CHUNK - 1) / CHACHA20_CHUNK; - if (blocks + ctx->c > CHACHA20_CTRMAX) + if (blocks + ctx->n[0] > CHACHA20_CTRMAX) return 0; *outlen = ctx->mlen + inlen - ((ctx->mlen + inlen) % CHACHA20_CHUNK); @@ -81,7 +81,7 @@ chacha20_common_update(void *arg, uint8_t *out, size_t *outlen, if (ctx->mlen == CHACHA20_CHUNK) { chacha20_block(ctx); - ctx->c++; + ctx->n[0]++; for (i = 0; i < CHACHA20_CHUNK_WORDS; i++) { h = load32le(&ctx->m[i * 4]); @@ -97,7 +97,7 @@ chacha20_common_update(void *arg, uint8_t *out, size_t *outlen, while (inlen >= CHACHA20_CHUNK) { chacha20_block(ctx); - ctx->c++; + ctx->n[0]++; for (i = 0; i < CHACHA20_CHUNK_WORDS; i++) { h = load32le(&in[i * 4]); diff --git a/impl_chacha20.c b/impl_chacha20.c index 0024340..b2d28c9 100644 --- a/impl_chacha20.c +++ b/impl_chacha20.c @@ -60,10 +60,10 @@ chacha20_block(struct chacha20_ctx *ctx) x[9] = ctx->k[5]; x[10] = ctx->k[6]; x[11] = ctx->k[7]; - x[12] = ctx->c; - x[13] = ctx->n[0]; - x[14] = ctx->n[1]; - x[15] = ctx->n[2]; + x[12] = ctx->n[0]; + x[13] = ctx->n[1]; + x[14] = ctx->n[2]; + x[15] = ctx->n[3]; for (i = 0; i < CHACHA20_CHUNK_WORDS; i++) ctx->s[i] = x[i]; diff --git a/impl_chacha20.h b/impl_chacha20.h index 9cac07e..6c85ec5 100644 --- a/impl_chacha20.h +++ b/impl_chacha20.h @@ -24,14 +24,13 @@ #define CHACHA20_CHUNK_WORDS (CHACHA20_CHUNK / sizeof(uint32_t)) #define CHACHA20_CTRMAX 4294967295 /* 2^32 - 1 */ #define CHACHA20_KEY_WORDS (LC_CHACHA20_KEYLEN / sizeof(uint32_t)) -#define CHACHA20_NONCE_WORDS (LC_CHACHA20_IVLEN / sizeof(uint32_t)) +#define CHACHA20_NONCE_WORDS 4 #define CHACHA20_ROUNDS 10 struct chacha20_ctx { uint32_t s[CHACHA20_CHUNK_WORDS]; uint32_t k[CHACHA20_KEY_WORDS]; - uint32_t c; uint32_t n[CHACHA20_NONCE_WORDS]; size_t mlen; uint8_t m[CHACHA20_CHUNK];