testutils.c: Fix high bits of the mpz_urandomb used with mini-gmp.
[gd/nettle] / chacha-crypt.c
1 /* chacha-crypt.c
2
3    The crypt function in the ChaCha stream cipher.
4    Heavily based on the Salsa20 implementation in Nettle.
5
6    Copyright (C) 2014 Niels Möller
7    Copyright (C) 2013 Joachim Strömbergson
8    Copyright (C) 2012 Simon Josefsson
9
10    This file is part of GNU Nettle.
11
12    GNU Nettle is free software: you can redistribute it and/or
13    modify it under the terms of either:
14
15      * the GNU Lesser General Public License as published by the Free
16        Software Foundation; either version 3 of the License, or (at your
17        option) any later version.
18
19    or
20
21      * the GNU General Public License as published by the Free
22        Software Foundation; either version 2 of the License, or (at your
23        option) any later version.
24
25    or both in parallel, as here.
26
27    GNU Nettle is distributed in the hope that it will be useful,
28    but WITHOUT ANY WARRANTY; without even the implied warranty of
29    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
30    General Public License for more details.
31
32    You should have received copies of the GNU General Public License and
33    the GNU Lesser General Public License along with this program.  If
34    not, see http://www.gnu.org/licenses/.
35 */
36
37 /* Based on:
38    chacha-ref.c version 2008.01.20.
39    D. J. Bernstein
40    Public domain.
41 */
42
43 #if HAVE_CONFIG_H
44 # include "config.h"
45 #endif
46
47 #include <string.h>
48
49 #include "chacha.h"
50
51 #include "macros.h"
52 #include "memxor.h"
53
54 #define CHACHA_ROUNDS 20
55
56 void
57 chacha_crypt(struct chacha_ctx *ctx,
58               size_t length,
59               uint8_t *c,
60               const uint8_t *m)
61 {
62   if (!length)
63     return;
64   
65   for (;;)
66     {
67       uint32_t x[_CHACHA_STATE_LENGTH];
68
69       _chacha_core (x, ctx->state, CHACHA_ROUNDS);
70
71       ctx->state[13] += (++ctx->state[12] == 0);
72
73       /* stopping at 2^70 length per nonce is user's responsibility */
74       
75       if (length <= CHACHA_BLOCK_SIZE)
76         {
77           memxor3 (c, m, x, length);
78           return;
79         }
80       memxor3 (c, m, x, CHACHA_BLOCK_SIZE);
81
82       length -= CHACHA_BLOCK_SIZE;
83       c += CHACHA_BLOCK_SIZE;
84       m += CHACHA_BLOCK_SIZE;
85   }
86 }