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