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