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