From 433af6d4bac8c3bff384abcb72399148346ad984 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Tue, 11 Sep 2018 10:22:28 -0400 Subject: [PATCH] drop 128-bit keys from ChaCha implementation --- chacha.c | 27 +++++++++------------------ chacha.h | 5 ++++- random.c | 9 +++------ 3 files changed, 16 insertions(+), 25 deletions(-) diff --git a/chacha.c b/chacha.c index 482b018..9674f29 100644 --- a/chacha.c +++ b/chacha.c @@ -41,30 +41,21 @@ Public domain. c = PLUS(c,d); b = ROTATE(XOR(b,c), 7); static const char sigma[16] = "expand 32-byte k"; -static const char tau[16] = "expand 16-byte k"; -void chacha_keysetup(chacha_ctx *x,const u8 *k,u32 kbits) +void chacha_keysetup(chacha_ctx *x,const u8 *k) { - const char *constants; - + x->input[0] = U8TO32_LITTLE(sigma + 0); + x->input[1] = U8TO32_LITTLE(sigma + 4); + x->input[2] = U8TO32_LITTLE(sigma + 8); + x->input[3] = U8TO32_LITTLE(sigma + 12); x->input[4] = U8TO32_LITTLE(k + 0); x->input[5] = U8TO32_LITTLE(k + 4); x->input[6] = U8TO32_LITTLE(k + 8); x->input[7] = U8TO32_LITTLE(k + 12); - if (kbits == 256) { /* recommended */ - k += 16; - constants = sigma; - } else { /* kbits == 128 */ - constants = tau; - } - x->input[8] = U8TO32_LITTLE(k + 0); - x->input[9] = U8TO32_LITTLE(k + 4); - x->input[10] = U8TO32_LITTLE(k + 8); - x->input[11] = U8TO32_LITTLE(k + 12); - x->input[0] = U8TO32_LITTLE(constants + 0); - x->input[1] = U8TO32_LITTLE(constants + 4); - x->input[2] = U8TO32_LITTLE(constants + 8); - x->input[3] = U8TO32_LITTLE(constants + 12); + x->input[8] = U8TO32_LITTLE(k + 16); + x->input[9] = U8TO32_LITTLE(k + 20); + x->input[10] = U8TO32_LITTLE(k + 24); + x->input[11] = U8TO32_LITTLE(k + 28); } void chacha_ivsetup(chacha_ctx *x,const u8 *iv) diff --git a/chacha.h b/chacha.h index 1f0b551..0a74233 100644 --- a/chacha.h +++ b/chacha.h @@ -3,6 +3,9 @@ #include +#define CHACHA_KEY_SIZE 32 +#define CHACHA_IV_SIZE 8 + typedef uint8_t u8; typedef uint32_t u32; @@ -11,7 +14,7 @@ typedef struct u32 input[16]; } chacha_ctx; -void chacha_keysetup(chacha_ctx *x,const u8 *k,u32 kbits); +void chacha_keysetup(chacha_ctx *x,const u8 *k); void chacha_ivsetup(chacha_ctx *x,const u8 *iv); void chacha_keystream_bytes(chacha_ctx *x,u8 *c,u32 bytes); diff --git a/random.c b/random.c index 8f54d3b..b966ab2 100644 --- a/random.c +++ b/random.c @@ -35,14 +35,11 @@ static void get_random_seed(void *buf, size_t size) { } } -#define KEY_SIZE 32 -#define IV_SIZE 8 - void random_state_init(struct random_state *state) { - uint8_t rnd[KEY_SIZE + IV_SIZE]; + uint8_t rnd[CHACHA_KEY_SIZE + CHACHA_IV_SIZE]; get_random_seed(rnd, sizeof(rnd)); - chacha_keysetup(&state->ctx, rnd, KEY_SIZE * 8); - chacha_ivsetup(&state->ctx, rnd + KEY_SIZE); + chacha_keysetup(&state->ctx, rnd); + chacha_ivsetup(&state->ctx, rnd + CHACHA_KEY_SIZE); chacha_keystream_bytes(&state->ctx, state->cache, RANDOM_CACHE_SIZE); state->index = 0; state->reseed = 0;