chiark / gitweb /
symm/poly1305.c: Fix daft typo in banner comment.
[catacomb] / symm / chacha.c
1 /* -*-c-*-
2  *
3  * ChaCha stream cipher
4  *
5  * (c) 2015 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Catacomb.
11  *
12  * Catacomb is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU Library General Public License as
14  * published by the Free Software Foundation; either version 2 of the
15  * License, or (at your option) any later version.
16  *
17  * Catacomb is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License along with Catacomb; if not, write to the Free
24  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25  * MA 02111-1307, USA.
26  */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #include "config.h"
31
32 #include <stdarg.h>
33
34 #include <mLib/bits.h>
35
36 #include "arena.h"
37 #include "chacha.h"
38 #include "chacha-core.h"
39 #include "dispatch.h"
40 #include "gcipher.h"
41 #include "grand.h"
42 #include "keysz.h"
43 #include "paranoia.h"
44
45 /*----- Global variables --------------------------------------------------*/
46
47 const octet chacha_keysz[] = { KSZ_SET, 32, 16, 10, 0 };
48
49 /*----- The ChaCha core function and utilities ----------------------------*/
50
51 /* --- @core@ --- *
52  *
53  * Arguments:   @unsigned r@ = number of rounds
54  *              @const chacha_matrix src@ = input matrix
55  *              @chacha_matrix dest@ = where to put the output
56  *
57  * Returns:     ---
58  *
59  *
60  * Use:         Apply the ChaCha/r core function to @src@, writing the
61  *              result to @dest@.  This consists of @r@ rounds followed by
62  *              the feedforward step.
63  */
64
65 CPU_DISPATCH(static, (void), void, core,
66              (unsigned r, const chacha_matrix src, chacha_matrix dest),
67              (r, src, dest), pick_core, simple_core);
68
69 static void simple_core(unsigned r, const chacha_matrix src,
70                         chacha_matrix dest)
71   { CHACHA_nR(dest, src, r); CHACHA_FFWD(dest, src); }
72
73 #if CPUFAM_X86 || CPUFAM_AMD64
74 extern core__functype chacha_core_x86ish_sse2;
75 #endif
76
77 #if CPUFAM_ARMEL
78 extern core__functype chacha_core_arm_neon;
79 #endif
80
81 static core__functype *pick_core(void)
82 {
83 #if CPUFAM_X86 || CPUFAM_AMD64
84   DISPATCH_PICK_COND(chacha_core, chacha_core_x86ish_sse2,
85                      cpu_feature_p(CPUFEAT_X86_SSE2));
86 #endif
87 #if CPUFAM_ARMEL
88   DISPATCH_PICK_COND(chacha_core, chacha_core_arm_neon,
89                      cpu_feature_p(CPUFEAT_ARM_NEON));
90 #endif
91   DISPATCH_PICK_FALLBACK(chacha_core, simple_core);
92 }
93
94 /* --- @populate@ --- *
95  *
96  * Arguments:   @chacha_matrix a@ = a matrix to fill in
97  *              @const void *key@ = pointer to key material
98  *              @size_t ksz@ = size of key
99  *
100  * Returns:     ---
101  *
102  * Use:         Fills in a ChaCha matrix from the key, setting the
103  *              appropriate constants according to the key length.  The nonce
104  *              and position words are left uninitialized.
105  */
106
107 static void populate(chacha_matrix a, const void *key, size_t ksz)
108 {
109   const octet *k = key;
110
111   KSZ_ASSERT(chacha, ksz);
112
113   a[ 4] = LOAD32_L(k +  0);
114   a[ 5] = LOAD32_L(k +  4);
115   if (ksz == 10) {
116     a[ 6] = LOAD16_L(k +  8);
117     a[ 7] = 0;
118   } else {
119     a[ 6] = LOAD32_L(k +  8);
120     a[ 7] = LOAD32_L(k + 12);
121   }
122   if (ksz <= 16) {
123     a[ 8] = a[ 4];
124     a[ 9] = a[ 5];
125     a[10] = a[ 6];
126     a[11] = a[ 7];
127     a[ 0] = CHACHA_A128;
128     a[ 1] = CHACHA_B128;
129     a[ 2] = ksz == 10 ? CHACHA_C80 : CHACHA_C128;
130     a[ 3] = CHACHA_D128;
131   } else {
132     a[ 8] = LOAD32_L(k + 16);
133     a[ 9] = LOAD32_L(k + 20);
134     a[10] = LOAD32_L(k + 24);
135     a[11] = LOAD32_L(k + 28);
136     a[ 0] = CHACHA_A256;
137     a[ 1] = CHACHA_B256;
138     a[ 2] = CHACHA_C256;
139     a[ 3] = CHACHA_D256;
140   }
141 }
142
143 /*----- ChaCha implementation ---------------------------------------------*/
144
145 /* --- @chacha_init@ --- *
146  *
147  * Arguments:   @chacha_ctx *ctx@ = context to fill in
148  *              @const void *key@ = pointer to key material
149  *              @size_t ksz@ = size of key (either 32 or 16)
150  *              @const void *nonce@ = initial nonce, or null
151  *
152  * Returns:     ---
153  *
154  * Use:         Initializes a ChaCha context ready for use.
155  */
156
157 void chacha_init(chacha_ctx *ctx, const void *key, size_t ksz,
158                   const void *nonce)
159 {
160   static const octet zerononce[CHACHA_NONCESZ];
161
162   populate(ctx->a, key, ksz);
163   chacha_setnonce(ctx, nonce ? nonce : zerononce);
164 }
165
166 /* --- @chacha_setnonce{,_ietf}@ --- *
167  *
168  * Arguments:   @chacha_ctx *ctx@ = pointer to context
169  *              @const void *nonce@ = the nonce (@CHACHA_NONCESZ@ or
170  *                      @CHACHA_IETF_NONCESZ@ bytes)
171  *
172  * Returns:     ---
173  *
174  * Use:         Set a new nonce in the context @ctx@, e.g., for processing a
175  *              different message.  The stream position is reset to zero (see
176  *              @chacha_seek@ etc.).
177  */
178
179 void chacha_setnonce(chacha_ctx *ctx, const void *nonce)
180 {
181   const octet *n = nonce;
182
183   ctx->a[14] = LOAD32_L(n + 0);
184   ctx->a[15] = LOAD32_L(n + 4);
185   chacha_seek(ctx, 0);
186 }
187
188 void chacha_setnonce_ietf(chacha_ctx *ctx, const void *nonce)
189 {
190   const octet *n = nonce;
191
192   ctx->a[13] = LOAD32_L(n + 0);
193   ctx->a[14] = LOAD32_L(n + 4);
194   ctx->a[15] = LOAD32_L(n + 8);
195   chacha_seek_ietf(ctx, 0);
196 }
197
198 /* --- @chacha_seek{,u64,_ietf}@ --- *
199  *
200  * Arguments:   @chacha_ctx *ctx@ = pointer to context
201  *              @unsigned long i@, @kludge64 i@, @uint32 i@ = new position
202  *
203  * Returns:     ---
204  *
205  * Use:         Sets a new stream position, in units of Chacha output
206  *              blocks, which are @CHACHA_OUTSZ@ bytes each.  Byte
207  *              granularity can be achieved by calling @chachaR_encrypt@
208  *              appropriately.
209  */
210
211 void chacha_seek(chacha_ctx *ctx, unsigned long i)
212   { kludge64 ii; ASSIGN64(ii, i); chacha_seeku64(ctx, ii); }
213
214 void chacha_seeku64(chacha_ctx *ctx, kludge64 i)
215 {
216   ctx->a[12] = LO64(i); ctx->a[13] = HI64(i);
217   ctx->bufi = CHACHA_OUTSZ;
218 }
219
220 void chacha_seek_ietf(chacha_ctx *ctx, uint32 i)
221   { ctx->a[12] = i; }
222
223 /* --- @chacha_tell{,u64,_ietf}@ --- *
224  *
225  * Arguments:   @chacha_ctx *ctx@ = pointer to context
226  *
227  * Returns:     The current position in the output stream, in blocks,
228  *              rounding upwards.
229  */
230
231 unsigned long chacha_tell(chacha_ctx *ctx)
232   { kludge64 i = chacha_tellu64(ctx); return (GET64(unsigned long, i)); }
233
234 kludge64 chacha_tellu64(chacha_ctx *ctx)
235   { kludge64 i; SET64(i, ctx->a[13], ctx->a[12]); return (i); }
236
237 uint32 chacha_tell_ietf(chacha_ctx *ctx)
238   { return (ctx->a[12]); }
239
240 /* --- @chacha{20,12,8}_encrypt@ --- *
241  *
242  * Arguments:   @chacha_ctx *ctx@ = pointer to context
243  *              @const void *src@ = source buffer (or null)
244  *              @void *dest@ = destination buffer (or null)
245  *              @size_t sz@ = size of the buffers
246  *
247  * Returns:     ---
248  *
249  * Use:         Encrypts or decrypts @sz@ bytes of data from @src@ to @dest@.
250  *              ChaCha works by XORing plaintext with a keystream, so
251  *              encryption and decryption are the same operation.  If @dest@
252  *              is null then ignore @src@ and skip @sz@ bytes of the
253  *              keystream.  If @src@ is null, then just write the keystream
254  *              to @dest@.
255  */
256
257 #define CHACHA_ENCRYPT(r, ctx, src, dest, sz)                           \
258   chacha##r##_encrypt(ctx, src, dest, sz)
259 #define DEFENCRYPT(r)                                                   \
260   void CHACHA_ENCRYPT(r, chacha_ctx *ctx, const void *src,              \
261                       void *dest, size_t sz)                            \
262   {                                                                     \
263     chacha_matrix b;                                                    \
264     const octet *s = src;                                               \
265     octet *d = dest;                                                    \
266     size_t n;                                                           \
267     kludge64 pos, delta;                                                \
268                                                                         \
269     SALSA20_OUTBUF(ctx, d, s, sz);                                      \
270     if (!sz) return;                                                    \
271                                                                         \
272     if (!dest) {                                                        \
273       n = sz/CHACHA_OUTSZ;                                              \
274       pos = chacha_tellu64(ctx);                                        \
275       ASSIGN64(delta, n);                                               \
276       ADD64(pos, pos, delta);                                           \
277       chacha_seeku64(ctx, pos);                                         \
278       sz = sz%CHACHA_OUTSZ;                                             \
279     } else if (!src) {                                                  \
280       while (sz >= CHACHA_OUTSZ) {                                      \
281         core(r, ctx->a, b);                                             \
282         CHACHA_STEP(ctx->a);                                            \
283         SALSA20_GENFULL(b, d);                                          \
284         sz -= CHACHA_OUTSZ;                                             \
285       }                                                                 \
286     } else {                                                            \
287       while (sz >= CHACHA_OUTSZ) {                                      \
288         core(r, ctx->a, b);                                             \
289         CHACHA_STEP(ctx->a);                                            \
290         SALSA20_MIXFULL(b, d, s);                                       \
291         sz -= CHACHA_OUTSZ;                                             \
292       }                                                                 \
293     }                                                                   \
294                                                                         \
295     if (sz) {                                                           \
296       core(r, ctx->a, b);                                               \
297       CHACHA_STEP(ctx->a);                                              \
298       SALSA20_PREPBUF(ctx, b);                                          \
299       SALSA20_OUTBUF(ctx, d, s, sz);                                    \
300       assert(!sz);                                                      \
301     }                                                                   \
302   }
303 CHACHA_VARS(DEFENCRYPT)
304
305 /*----- HChaCha implementation --------------------------------------------*/
306
307 #define HCHACHA_RAW(r, ctx, src, dest) hchacha##r##_raw(ctx, src, dest)
308 #define HCHACHA_PRF(r, ctx, src, dest) hchacha##r##_prf(ctx, src, dest)
309
310 /* --- @hchacha{20,12,8}_prf@ --- *
311  *
312  * Arguments:   @chacha_ctx *ctx@ = pointer to context
313  *              @const void *src@ = the input (@HCHACHA_INSZ@ bytes)
314  *              @void *dest@ = the output (@HCHACHA_OUTSZ@ bytes)
315  *
316  * Returns:     ---
317  *
318  * Use:         Apply the HChacha/r pseudorandom function to @src@, writing
319  *              the result to @out@.
320  */
321
322 #define DEFHCHACHA(r)                                                   \
323   static void HCHACHA_RAW(r, chacha_matrix k,                           \
324                           const uint32 *src, uint32 *dest)              \
325   {                                                                     \
326     chacha_matrix a;                                                    \
327     int i;                                                              \
328                                                                         \
329     /* --- HChaCha, computed from full ChaCha --- *                     \
330      *                                                                  \
331      * The security proof makes use of the fact that HChaCha (i.e.,     \
332      * without the final feedforward step) can be computed from full    \
333      * ChaCha using only knowledge of the non-secret input.  I don't    \
334      * want to compromise the performance of the main function by       \
335      * making the feedforward step separate, but this operation is less \
336      * speed critical, so we do it the harder way.                      \
337      */                                                                 \
338                                                                         \
339     for (i = 0; i < 4; i++) k[12 + i] = src[i];                         \
340     core(r, k, a);                                                      \
341     for (i = 0; i < 8; i++) dest[i] = a[(i + 4)^4] - k[(i + 4)^4];      \
342   }                                                                     \
343                                                                         \
344   void HCHACHA_PRF(r, chacha_ctx *ctx, const void *src, void *dest)     \
345   {                                                                     \
346     const octet *s = src;                                               \
347     octet *d = dest;                                                    \
348     uint32 in[4], out[8];                                               \
349     int i;                                                              \
350                                                                         \
351     for (i = 0; i < 4; i++) in[i] = LOAD32_L(s + 4*i);                  \
352     HCHACHA_RAW(r, ctx->a, in, out);                                    \
353     for (i = 0; i < 8; i++) STORE32_L(d + 4*i, out[i]);                 \
354   }
355 CHACHA_VARS(DEFHCHACHA)
356
357 /*----- XChaCha implementation -------------------------------------------*/
358
359 /* --- Some convenient macros for naming functions --- *
360  *
361  * Because the crypto core is involved in XChaCha/r's per-nonce setup, we
362  * need to take an interest in the number of rounds in most of the various
363  * functions, and it will probably help if we distinguish the context
364  * structures for the various versions.
365  */
366
367 #define XCHACHA_CTX(r) xchacha##r##_ctx
368 #define XCHACHA_INIT(r, ctx, k, ksz, n) xchacha##r##_init(ctx, k, ksz, n)
369 #define XCHACHA_SETNONCE(r, ctx, n) xchacha##r##_setnonce(ctx, n)
370 #define XCHACHA_SEEK(r, ctx, i) xchacha##r##_seek(ctx, i)
371 #define XCHACHA_SEEKU64(r, ctx, i) xchacha##r##_seeku64(ctx, i)
372 #define XCHACHA_TELL(r, ctx) xchacha##r##_tell(ctx)
373 #define XCHACHA_TELLU64(r, ctx) xchacha##r##_tellu64(ctx)
374 #define XCHACHA_ENCRYPT(r, ctx, src, dest, sz)                          \
375   xchacha##r##_encrypt(ctx, src, dest, sz)
376
377 /* --- @xchacha{20,12,8}_init@ --- *
378  *
379  * Arguments:   @xchachaR_ctx *ctx@ = the context to fill in
380  *              @const void *key@ = pointer to key material
381  *              @size_t ksz@ = size of key (either 32 or 16)
382  *              @const void *nonce@ = initial nonce, or null
383  *
384  * Returns:     ---
385  *
386  * Use:         Initializes an XChaCha/r context ready for use.
387  *
388  *              There is a different function for each number of rounds,
389  *              unlike for plain ChaCha.
390  */
391
392 #define DEFXINIT(r)                                                     \
393   void XCHACHA_INIT(r, XCHACHA_CTX(r) *ctx,                             \
394                     const void *key, size_t ksz, const void *nonce)     \
395   {                                                                     \
396     static const octet zerononce[XCHACHA_NONCESZ];                      \
397                                                                         \
398     populate(ctx->k, key, ksz);                                         \
399     ctx->s.a[ 0] = CHACHA_A256;                                         \
400     ctx->s.a[ 1] = CHACHA_B256;                                         \
401     ctx->s.a[ 2] = CHACHA_C256;                                         \
402     ctx->s.a[ 3] = CHACHA_D256;                                         \
403     XCHACHA_SETNONCE(r, ctx, nonce ? nonce : zerononce);                \
404   }
405 CHACHA_VARS(DEFXINIT)
406
407 /* --- @xchacha{20,12,8}_setnonce@ --- *
408  *
409  * Arguments:   @xchachaR_ctx *ctx@ = pointer to context
410  *              @const void *nonce@ = the nonce (@XCHACHA_NONCESZ@ bytes)
411  *
412  * Returns:     ---
413  *
414  * Use:         Set a new nonce in the context @ctx@, e.g., for processing a
415  *              different message.  The stream position is reset to zero (see
416  *              @chacha_seek@ etc.).
417  *
418  *              There is a different function for each number of rounds,
419  *              unlike for plain ChaCha.
420  */
421
422 #define DEFXNONCE(r)                                                    \
423   void XCHACHA_SETNONCE(r, XCHACHA_CTX(r) *ctx, const void *nonce)      \
424   {                                                                     \
425     const octet *n = nonce;                                             \
426     uint32 in[4];                                                       \
427     int i;                                                              \
428                                                                         \
429     for (i = 0; i < 4; i++) in[i] = LOAD32_L(n + 4*i);                  \
430     HCHACHA_RAW(r, ctx->k, in, ctx->s.a + 4);                           \
431     chacha_setnonce(&ctx->s, n + 16);                                   \
432   }
433 CHACHA_VARS(DEFXNONCE)
434
435 /* --- @xchacha{20,12,8}_seek{,u64}@ --- *
436  *
437  * Arguments:   @xchachaR_ctx *ctx@ = pointer to context
438  *              @unsigned long i@, @kludge64 i@ = new position to set
439  *
440  * Returns:     ---
441  *
442  * Use:         Sets a new stream position, in units of ChaCha output
443  *              blocks, which are @XCHACHA_OUTSZ@ bytes each.  Byte
444  *              granularity can be achieved by calling @xchachaR_encrypt@
445  *              appropriately.
446  *
447  *              There is a different function for each number of rounds,
448  *              unlike for plain ChaCha, because the context structures are
449  *              different.
450  */
451
452 /* --- @xchacha{20,12,8}_tell{,u64}@ --- *
453  *
454  * Arguments:   @chacha_ctx *ctx@ = pointer to context
455  *
456  * Returns:     The current position in the output stream, in blocks,
457  *              rounding upwards.
458  *
459  *              There is a different function for each number of rounds,
460  *              unlike for plain ChaCha, because the context structures are
461  *              different.
462  */
463
464 /* --- @xchacha{20,12,8}_encrypt@ --- *
465  *
466  * Arguments:   @xchachaR_ctx *ctx@ = pointer to context
467  *              @const void *src@ = source buffer (or null)
468  *              @void *dest@ = destination buffer (or null)
469  *              @size_t sz@ = size of the buffers
470  *
471  * Returns:     ---
472  *
473  * Use:         Encrypts or decrypts @sz@ bytes of data from @src@ to @dest@.
474  *              XChaCha works by XORing plaintext with a keystream, so
475  *              encryption and decryption are the same operation.  If @dest@
476  *              is null then ignore @src@ and skip @sz@ bytes of the
477  *              keystream.  If @src@ is null, then just write the keystream
478  *              to @dest@.
479  */
480
481 #define DEFXPASSTHRU(r)                                                 \
482   void XCHACHA_SEEK(r, XCHACHA_CTX(r) *ctx, unsigned long i)            \
483     { chacha_seek(&ctx->s, i); }                                        \
484   void XCHACHA_SEEKU64(r, XCHACHA_CTX(r) *ctx, kludge64 i)              \
485     { chacha_seeku64(&ctx->s, i); }                                     \
486   unsigned long XCHACHA_TELL(r, XCHACHA_CTX(r) *ctx)                    \
487     { return chacha_tell(&ctx->s); }                                    \
488   kludge64 XCHACHA_TELLU64(r, XCHACHA_CTX(r) *ctx)                      \
489     { return chacha_tellu64(&ctx->s); }                                 \
490   void XCHACHA_ENCRYPT(r, XCHACHA_CTX(r) *ctx,                          \
491                         const void *src, void *dest, size_t sz)         \
492     { CHACHA_ENCRYPT(r, &ctx->s, src, dest, sz); }
493 CHACHA_VARS(DEFXPASSTHRU)
494
495 /*----- Generic cipher interface ------------------------------------------*/
496
497 typedef struct gctx { gcipher c; chacha_ctx ctx; } gctx;
498
499 static void gsetiv(gcipher *c, const void *iv)
500   { gctx *g = (gctx *)c; chacha_setnonce(&g->ctx, iv); }
501
502 static void gsetiv_ietf(gcipher *c, const void *iv)
503   { gctx *g = (gctx *)c; chacha_setnonce_ietf(&g->ctx, iv); }
504
505 static void gdestroy(gcipher *c)
506   { gctx *g = (gctx *)c; BURN(*g); S_DESTROY(g); }
507
508 static gcipher *ginit(const void *k, size_t sz, const gcipher_ops *ops)
509 {
510   gctx *g = S_CREATE(gctx);
511   g->c.ops = ops;
512   chacha_init(&g->ctx, k, sz, 0);
513   return (&g->c);
514 }
515
516 #define DEFGCIPHER(r)                                                   \
517                                                                         \
518   static const gcipher_ops gops_##r, gops_##r##_ietf;                   \
519                                                                         \
520   static gcipher *ginit_##r(const void *k, size_t sz)                   \
521     { return (ginit(k, sz, &gops_##r)); }                               \
522                                                                         \
523   static gcipher *ginit_##r##_ietf(const void *k, size_t sz)            \
524     { return (ginit(k, sz, &gops_##r##_ietf)); }                        \
525                                                                         \
526   static void gencrypt_##r(gcipher *c, const void *s,                   \
527                            void *t, size_t sz)                          \
528     { gctx *g = (gctx *)c; CHACHA_ENCRYPT(r, &g->ctx, s, t, sz); }      \
529                                                                         \
530   static const gcipher_ops gops_##r = {                                 \
531     &chacha##r,                                                         \
532     gencrypt_##r, gencrypt_##r, gdestroy, gsetiv, 0                     \
533   };                                                                    \
534                                                                         \
535   static const gcipher_ops gops_##r##_ietf = {                          \
536     &chacha##r##_ietf,                                                  \
537     gencrypt_##r, gencrypt_##r, gdestroy, gsetiv_ietf, 0                \
538   };                                                                    \
539                                                                         \
540   const gccipher chacha##r = {                                          \
541     "chacha" #r, chacha_keysz,                                          \
542     CHACHA_NONCESZ, ginit_##r                                           \
543   };                                                                    \
544                                                                         \
545   const gccipher chacha##r##_ietf = {                                   \
546     "chacha" #r "-ietf", chacha_keysz,                                  \
547     CHACHA_IETF_NONCESZ, ginit_##r##_ietf                               \
548   };
549
550 CHACHA_VARS(DEFGCIPHER)
551
552 #define DEFGXCIPHER(r)                                                  \
553                                                                         \
554   typedef struct { gcipher c; XCHACHA_CTX(r) ctx; } gxctx_##r;          \
555                                                                         \
556   static void gxsetiv_##r(gcipher *c, const void *iv)                   \
557     { gxctx_##r *g = (gxctx_##r *)c; XCHACHA_SETNONCE(r, &g->ctx, iv); } \
558                                                                         \
559   static void gxdestroy_##r(gcipher *c)                                 \
560     { gxctx_##r *g = (gxctx_##r *)c; BURN(*g); S_DESTROY(g); }          \
561                                                                         \
562   static const gcipher_ops gxops_##r;                                   \
563                                                                         \
564   static gcipher *gxinit_##r(const void *k, size_t sz)                  \
565   {                                                                     \
566     gxctx_##r *g = S_CREATE(gxctx_##r);                                 \
567     g->c.ops = &gxops_##r;                                              \
568     XCHACHA_INIT(r, &g->ctx, k, sz, 0);                                 \
569     return (&g->c);                                                     \
570   }                                                                     \
571                                                                         \
572   static void gxencrypt_##r(gcipher *c, const void *s,                  \
573                             void *t, size_t sz)                         \
574   {                                                                     \
575     gxctx_##r *g = (gxctx_##r *)c;                                      \
576     XCHACHA_ENCRYPT(r, &g->ctx, s, t, sz);                              \
577   }                                                                     \
578                                                                         \
579   static const gcipher_ops gxops_##r = {                                \
580     &xchacha##r,                                                        \
581     gxencrypt_##r, gxencrypt_##r, gxdestroy_##r, gxsetiv_##r, 0         \
582   };                                                                    \
583                                                                         \
584   const gccipher xchacha##r = {                                         \
585     "xchacha" #r, chacha_keysz,                                         \
586     CHACHA_NONCESZ, gxinit_##r                                          \
587   };
588
589 CHACHA_VARS(DEFGXCIPHER)
590
591 /*----- Generic random number generator interface -------------------------*/
592
593 typedef struct grops {
594   size_t noncesz;
595   void (*seek)(void *, kludge64);
596   kludge64 (*tell)(void *);
597   void (*setnonce)(void *, const void *);
598   void (*generate)(void *, void *, size_t);
599 } grops;
600
601 typedef struct grbasectx {
602   grand r;
603   const grops *ops;
604 } grbasectx;
605
606 static int grmisc(grand *r, unsigned op, ...)
607 {
608   octet buf[XCHACHA_NONCESZ];
609   grbasectx *g = (grbasectx *)r;
610   grand *rr;
611   const octet *p;
612   size_t sz;
613   uint32 i;
614   unsigned long ul;
615   kludge64 pos;
616   va_list ap;
617   int rc = 0;
618
619   va_start(ap, op);
620
621   switch (op) {
622     case GRAND_CHECK:
623       switch (va_arg(ap, unsigned)) {
624         case GRAND_CHECK:
625         case GRAND_SEEDINT:
626         case GRAND_SEEDUINT32:
627         case GRAND_SEEDBLOCK:
628         case GRAND_SEEDRAND:
629         case CHACHA_SEEK:
630         case CHACHA_SEEKU64:
631         case CHACHA_TELL:
632         case CHACHA_TELLU64:
633           rc = 1;
634           break;
635         default:
636           rc = 0;
637           break;
638       }
639       break;
640
641     case GRAND_SEEDINT:
642       i = va_arg(ap, unsigned); STORE32_L(buf, i);
643       memset(buf + 4, 0, g->ops->noncesz - 4);
644       g->ops->setnonce(g, buf);
645       break;
646     case GRAND_SEEDUINT32:
647       i = va_arg(ap, uint32); STORE32_L(buf, i);
648       memset(buf + 4, 0, g->ops->noncesz - 4);
649       g->ops->setnonce(g, buf);
650       break;
651     case GRAND_SEEDBLOCK:
652       p = va_arg(ap, const void *);
653       sz = va_arg(ap, size_t);
654       if (sz < g->ops->noncesz) {
655         memcpy(buf, p, sz);
656         memset(buf + sz, 0, g->ops->noncesz - sz);
657         p = buf;
658       }
659       g->ops->setnonce(g, p);
660       break;
661     case GRAND_SEEDRAND:
662       rr = va_arg(ap, grand *);
663       rr->ops->fill(rr, buf, g->ops->noncesz);
664       g->ops->setnonce(g, buf);
665       break;
666     case CHACHA_SEEK:
667       ul = va_arg(ap, unsigned long); ASSIGN64(pos, ul);
668       g->ops->seek(g, pos);
669       break;
670     case CHACHA_SEEKU64:
671       pos = va_arg(ap, kludge64);
672       g->ops->seek(g, pos);
673       break;
674     case CHACHA_TELL:
675       pos = g->ops->tell(g);
676       *va_arg(ap, unsigned long *) = GET64(unsigned long, pos);
677       break;
678     case CHACHA_TELLU64:
679       *va_arg(ap, kludge64 *) = g->ops->tell(g);
680       break;
681     default:
682       GRAND_BADOP;
683       break;
684   }
685
686   return (rc);
687 }
688
689 static octet grbyte(grand *r)
690 {
691   grbasectx *g = (grbasectx *)r;
692   octet o;
693   g->ops->generate(g, &o, 1);
694   return (o);
695 }
696
697 static uint32 grword(grand *r)
698 {
699   grbasectx *g = (grbasectx *)r;
700   octet b[4];
701   g->ops->generate(g, b, sizeof(b));
702   return (LOAD32_L(b));
703 }
704
705 static void grfill(grand *r, void *p, size_t sz)
706 {
707   grbasectx *g = (grbasectx *)r;
708   g->ops->generate(r, p, sz);
709 }
710
711 typedef struct grctx {
712   grbasectx r;
713   chacha_ctx ctx;
714 } grctx;
715
716 static void gr_seek(void *r, kludge64 pos)
717   { grctx *g = r; chacha_seeku64(&g->ctx, pos); }
718
719 static void gr_seek_ietf(void *r, kludge64 pos)
720   { grctx *g = r; chacha_seek_ietf(&g->ctx, LO64(pos)); }
721
722 static kludge64 gr_tell(void *r)
723   { grctx *g = r; return (chacha_tellu64(&g->ctx)); }
724
725 static kludge64 gr_tell_ietf(void *r)
726 {
727   grctx *g = r;
728   kludge64 pos;
729
730   SET64(pos, 0, chacha_tell_ietf(&g->ctx));
731   return (pos);
732 }
733
734 static void gr_setnonce(void *r, const void *n)
735   { grctx *g = r; chacha_setnonce(&g->ctx, n); }
736
737 static void gr_setnonce_ietf(void *r, const void *n)
738   { grctx *g = r; chacha_setnonce_ietf(&g->ctx, n); }
739
740 static void grdestroy(grand *r)
741   { grctx *g = (grctx *)r; BURN(*g); S_DESTROY(g); }
742
743 static grand *grinit(const void *k, size_t ksz, const void *n,
744                      const grand_ops *ops, const grops *myops)
745 {
746     grctx *g = S_CREATE(grctx);
747     g->r.r.ops = ops;
748     g->r.ops = myops;
749     chacha_init(&g->ctx, k, ksz, 0);
750     if (n) myops->setnonce(g, n);
751     return (&g->r.r);
752 }
753
754 #define DEFGRAND(rr)                                                    \
755                                                                         \
756   static void gr_generate_##rr(void *r, void *b, size_t sz)             \
757     { grctx *g = r; CHACHA_ENCRYPT(rr, &g->ctx, 0, b, sz); }            \
758                                                                         \
759   static const grops grops_##rr =                                       \
760     { CHACHA_NONCESZ, gr_seek, gr_tell,                                 \
761       gr_setnonce, gr_generate_##rr };                                  \
762                                                                         \
763   static const grops grops_##rr##_ietf =                                \
764     { CHACHA_IETF_NONCESZ, gr_seek_ietf, gr_tell_ietf,                  \
765       gr_setnonce_ietf, gr_generate_##rr };                             \
766                                                                         \
767   static const grand_ops grops_rand_##rr = {                            \
768     "chacha" #rr, GRAND_CRYPTO, 0,                                      \
769     grmisc, grdestroy, grword,                                          \
770     grbyte, grword, grand_defaultrange, grfill                          \
771   };                                                                    \
772                                                                         \
773   static const grand_ops grops_rand_##rr##_ietf = {                     \
774     "chacha" #rr "-ietf", GRAND_CRYPTO, 0,                              \
775     grmisc, grdestroy, grword,                                          \
776     grbyte, grword, grand_defaultrange, grfill                          \
777   };                                                                    \
778                                                                         \
779   grand *chacha##rr##_rand(const void *k, size_t ksz, const void *n)    \
780     { return (grinit(k, ksz, n, &grops_rand_##rr, &grops_##rr)); }      \
781                                                                         \
782   grand *chacha##rr##_ietf_rand(const void *k, size_t ksz,              \
783                                 const void *n)                          \
784   {                                                                     \
785     return (grinit(k, ksz, n,                                           \
786                    &grops_rand_##rr##_ietf,                             \
787                    &grops_##rr##_ietf));                                \
788   }
789
790 CHACHA_VARS(DEFGRAND)
791
792 #define DEFXGRAND(rr)                                                   \
793                                                                         \
794   typedef struct grxctx_##rr {                                          \
795     grbasectx r;                                                        \
796     XCHACHA_CTX(rr) ctx;                                                \
797   } grxctx_##rr;                                                        \
798                                                                         \
799   static void grx_seek_##rr(void *r, kludge64 pos)                      \
800     { grxctx_##rr *g = r; XCHACHA_SEEKU64(rr, &g->ctx, pos); }          \
801                                                                         \
802   static kludge64 grx_tell_##rr(void *r)                                \
803     { grxctx_##rr *g = r; return (XCHACHA_TELLU64(rr, &g->ctx)); }      \
804                                                                         \
805   static void grx_setnonce_##rr(void *r, const void *n)                 \
806     { grxctx_##rr *g = r; XCHACHA_SETNONCE(rr, &g->ctx, n); }           \
807                                                                         \
808   static void grxdestroy_##rr(grand *r)                                 \
809     { grxctx_##rr *g = (grxctx_##rr *)r; BURN(*g); S_DESTROY(g); }      \
810                                                                         \
811   static void grx_generate_##rr(void *r, void *b, size_t sz)            \
812     { grxctx_##rr *g = r; XCHACHA_ENCRYPT(rr, &g->ctx, 0, b, sz); }     \
813                                                                         \
814   static const grops grxops_##rr =                                      \
815     { XCHACHA_NONCESZ, grx_seek_##rr, grx_tell_##rr,                    \
816       grx_setnonce_##rr, grx_generate_##rr };                           \
817                                                                         \
818   static const grand_ops grxops_rand_##rr = {                           \
819     "xchacha" #rr, GRAND_CRYPTO, 0,                                     \
820     grmisc, grxdestroy_##rr, grword,                                    \
821     grbyte, grword, grand_defaultrange, grfill                          \
822   };                                                                    \
823                                                                         \
824   grand *xchacha##rr##_rand(const void *k, size_t ksz, const void *n)   \
825   {                                                                     \
826     grxctx_##rr *g = S_CREATE(grxctx_##rr);                             \
827     g->r.r.ops = &grxops_rand_##rr;                                     \
828     g->r.ops = &grxops_##rr;                                            \
829     XCHACHA_INIT(rr, &g->ctx, k, ksz, n);                               \
830     return (&g->r.r);                                                   \
831   }
832 CHACHA_VARS(DEFXGRAND)
833
834 /*----- Test rig ----------------------------------------------------------*/
835
836 #ifdef TEST_RIG
837
838 #include <stdio.h>
839 #include <string.h>
840
841 #include <mLib/quis.h>
842 #include <mLib/testrig.h>
843
844 #define DEFVCORE(r)                                                     \
845   static int v_core_##r(dstr *v)                                        \
846   {                                                                     \
847     chacha_matrix a, b;                                                 \
848     dstr d = DSTR_INIT;                                                 \
849     int i, n;                                                           \
850     int ok = 1;                                                         \
851                                                                         \
852     DENSURE(&d, CHACHA_OUTSZ); d.len = CHACHA_OUTSZ;                    \
853     n = *(int *)v[0].buf;                                               \
854     for (i = 0; i < CHACHA_OUTSZ/4; i++)                                \
855       a[i] = LOAD32_L(v[1].buf + 4*i);                                  \
856     for (i = 0; i < n; i++) {                                           \
857       core(r, a, b);                                                    \
858       memcpy(a, b, sizeof(a));                                          \
859     }                                                                   \
860     for (i = 0; i < CHACHA_OUTSZ/4; i++) STORE32_L(d.buf + 4*i, a[i]);  \
861                                                                         \
862     if (d.len != v[2].len || memcmp(d.buf, v[2].buf, v[2].len) != 0) {  \
863       ok = 0;                                                           \
864       printf("\nfail core:"                                             \
865              "\n\titerations = %d"                                      \
866              "\n\tin       = ", n);                                     \
867       type_hex.dump(&v[1], stdout);                                     \
868       printf("\n\texpected   = ");                                      \
869       type_hex.dump(&v[2], stdout);                                     \
870       printf("\n\tcalculated = ");                                      \
871       type_hex.dump(&d, stdout);                                        \
872       putchar('\n');                                                    \
873     }                                                                   \
874                                                                         \
875     dstr_destroy(&d);                                                   \
876     return (ok);                                                        \
877   }
878 CHACHA_VARS(DEFVCORE)
879
880 #define CHACHA_CTX(r) chacha_ctx
881
882 #define CHACHA_TESTSETUP(r, ctx, k, ksz, n, nsz, p, psz) do {           \
883   kludge64 pos64;                                                       \
884   chacha_init(ctx, k, ksz, 0);                                          \
885   if (nsz == 8) chacha_setnonce(ctx, n);                                \
886   else if (nsz == 12) chacha_setnonce_ietf(ctx, n);                     \
887   if (psz == 8) { LOAD64_(pos64, p); chacha_seeku64(ctx, pos64); }      \
888   else if (psz == 4) chacha_seek_ietf(ctx, LOAD32(p));                  \
889 } while (0)
890
891 #define XCHACHA_TESTSETUP(r, ctx, k, ksz, n, nsz, p, psz) do {          \
892   kludge64 pos64;                                                       \
893   XCHACHA_INIT(r, ctx, k, ksz, 0);                                      \
894   if (nsz == 24) XCHACHA_SETNONCE(r, ctx, n);                           \
895   if (psz == 8) { LOAD64_(pos64, p); xchacha##r##_seeku64(ctx, pos64); } \
896 } while (0)
897
898 #define DEFxVENC(base, BASE, r)                                         \
899   static int v_encrypt_##base##_##r(dstr *v)                            \
900   {                                                                     \
901     BASE##_CTX(r) ctx;                                                  \
902     dstr d = DSTR_INIT;                                                 \
903     const octet *p, *p0;                                                \
904     octet *q;                                                           \
905     size_t sz, sz0, step;                                               \
906     unsigned long skip;                                                 \
907     int ok = 1;                                                         \
908                                                                         \
909     if (v[4].len) { p0 = (const octet *)v[4].buf; sz0 = v[4].len; }     \
910     else { p0 = 0; sz0 = v[5].len; }                                    \
911     DENSURE(&d, sz0); d.len = sz0;                                      \
912     skip = *(unsigned long *)v[3].buf;                                  \
913                                                                         \
914     step = 0;                                                           \
915     while (step < sz0 + skip) {                                         \
916       step = step ? 3*step + 4 : 1;                                     \
917       if (step > sz0 + skip) step = sz0 + skip;                         \
918       BASE##_TESTSETUP(r, &ctx, v[0].buf, v[0].len,                     \
919                        v[1].buf, v[1].len, v[2].buf, v[2].len);         \
920                                                                         \
921       for (sz = skip; sz >= step; sz -= step)                           \
922         BASE##_ENCRYPT(r, &ctx, 0, 0, step);                            \
923       if (sz) BASE##_ENCRYPT(r, &ctx, 0, 0, sz);                        \
924       for (p = p0, q = (octet *)d.buf, sz = sz0;                        \
925            sz >= step;                                                  \
926            sz -= step, q += step) {                                     \
927         BASE##_ENCRYPT(r, &ctx, p, q, step);                            \
928         if (p) p += step;                                               \
929       }                                                                 \
930       if (sz) BASE##_ENCRYPT(r, &ctx, p, q, sz);                        \
931                                                                         \
932       if (d.len != v[5].len || memcmp(d.buf, v[5].buf, v[5].len) != 0) { \
933         ok = 0;                                                         \
934         printf("\nfail encrypt:"                                        \
935                "\n\tstep           = %lu"                               \
936                "\n\tkey    = ", (unsigned long)step);                   \
937         type_hex.dump(&v[0], stdout);                                   \
938         printf("\n\tnonce          = ");                                \
939         type_hex.dump(&v[1], stdout);                                   \
940         printf("\n\tposition   = ");                                    \
941         type_hex.dump(&v[2], stdout);                                   \
942         printf("\n\tskip           = %lu", skip);                       \
943         printf("\n\tmessage    = ");                                    \
944         type_hex.dump(&v[4], stdout);                                   \
945         printf("\n\texpected   = ");                                    \
946         type_hex.dump(&v[5], stdout);                                   \
947         printf("\n\tcalculated = ");                                    \
948         type_hex.dump(&d, stdout);                                      \
949         putchar('\n');                                                  \
950       }                                                                 \
951     }                                                                   \
952                                                                         \
953     dstr_destroy(&d);                                                   \
954     return (ok);                                                        \
955   }
956 #define DEFVENC(r) DEFxVENC(chacha, CHACHA, r)
957 #define DEFXVENC(r) DEFxVENC(xchacha, XCHACHA, r)
958 CHACHA_VARS(DEFVENC)
959 CHACHA_VARS(DEFXVENC)
960
961 static test_chunk defs[] = {
962 #define DEFxTAB(base, r)                                                \
963   { #base #r, v_encrypt_##base##_##r,                                   \
964     { &type_hex, &type_hex, &type_hex, &type_ulong,                     \
965       &type_hex, &type_hex, 0 } },
966 #define DEFTAB(r)                                                       \
967   { "chacha" #r "-core", v_core_##r,                                    \
968     { &type_int, &type_hex, &type_hex, 0 } },                           \
969   DEFxTAB(chacha, r)
970 #define DEFXTAB(r) DEFxTAB(xchacha, r)
971 CHACHA_VARS(DEFTAB)
972 CHACHA_VARS(DEFXTAB)
973   { 0, 0, { 0 } }
974 };
975
976 int main(int argc, char *argv[])
977 {
978   test_run(argc, argv, defs, SRCDIR"/t/chacha");
979   return (0);
980 }
981
982 #endif
983
984 /*----- That's all, folks -------------------------------------------------*/