cipher/chacha20: treat the counter as part of the nonce
This commit is contained in:
parent
b793cb5b69
commit
06f835e27c
@ -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]);
|
||||
|
@ -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];
|
||||
|
@ -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];
|
||||
|
Loading…
Reference in New Issue
Block a user