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