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