chiark / gitweb /
math/pgen.c: Don't free the tester if it's not set up.
[catacomb] / symm / counter-def.h
1 /* -*-c-*-
2  *
3  * Block cipher counter mode (or long cycle mode)
4  *
5  * (c) 2000 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 #ifndef CATACOMB_COUNTER_DEF_H
29 #define CATACOMB_COUNTER_DEF_H
30
31 #ifdef __cplusplus
32   extern "C" {
33 #endif
34
35 /*----- Header files ------------------------------------------------------*/
36
37 #include <stdarg.h>
38 #include <string.h>
39
40 #include <mLib/bits.h>
41 #include <mLib/sub.h>
42
43 #ifndef CATACOMB_ARENA_H
44 #  include "arena.h"
45 #endif
46
47 #ifndef CATACOMB_BLKC_H
48 #  include "blkc.h"
49 #endif
50
51 #ifndef CATACOMB_GCIPHER_H
52 #  include "gcipher.h"
53 #endif
54
55 #ifndef CATACOMB_PARANOIA_H
56 #  include "paranoia.h"
57 #endif
58
59 /*----- Macros ------------------------------------------------------------*/
60
61 /* --- @COUNTER_DEF@ --- *
62  *
63  * Arguments:   @PRE@, @pre@ = prefixes for the underlying block cipher
64  *
65  * Use:         Creates definitions for counter mode.
66  */
67
68 #define COUNTER_DEF(PRE, pre) COUNTER_DEFX(PRE, pre, #pre, #pre)
69
70 #define COUNTER_DEFX(PRE, pre, name, fname)                             \
71                                                                         \
72 /* --- @pre_countergetiv@ --- *                                         \
73  *                                                                      \
74  * Arguments:   @const pre_counterctx *ctx@ = pointer to counter        \
75  *                      context                                         \
76  *              @void *iv@ = pointer to output data block               \
77  *                                                                      \
78  * Returns:     ---                                                     \
79  *                                                                      \
80  * Use:         Reads the currently set IV.  Reading and setting an IV  \
81  *              is not transparent to the cipher.  It will add a `step' \
82  *              which must be matched by a similar operation during     \
83  *              decryption.                                             \
84  */                                                                     \
85                                                                         \
86 void pre##_countergetiv(const pre##_counterctx *ctx, void *iv)          \
87 {                                                                       \
88   BLKC_STORE(PRE, iv, ctx->n);                                          \
89 }                                                                       \
90                                                                         \
91 /* --- @pre_countersetiv@ --- *                                         \
92  *                                                                      \
93  * Arguments:   @pre_counterctx *ctx@ = pointer to counter context      \
94  *              @cnost void *iv@ = pointer to IV to set                 \
95  *                                                                      \
96  * Returns:     ---                                                     \
97  *                                                                      \
98  * Use:         Sets the IV to use for subsequent encryption.           \
99  */                                                                     \
100                                                                         \
101 void pre##_countersetiv(pre##_counterctx *ctx, const void *iv)          \
102 {                                                                       \
103   BLKC_LOAD(PRE, ctx->n, iv);                                           \
104   ctx->off = PRE##_BLKSZ;                                               \
105 }                                                                       \
106                                                                         \
107 /* --- @pre_counterbdry@ --- *                                          \
108  *                                                                      \
109  * Arguments:   @pre_counterctx *ctx@ = pointer to counter context      \
110  *                                                                      \
111  * Returns:     ---                                                     \
112  *                                                                      \
113  * Use:         Inserts a boundary during encryption.  Successful       \
114  *              decryption must place a similar boundary.               \
115  */                                                                     \
116                                                                         \
117 void pre##_counterbdry(pre##_counterctx *ctx)                           \
118 {                                                                       \
119   BLKC_STEP(PRE, ctx->n);                                               \
120   ctx->off = PRE##_BLKSZ;                                               \
121 }                                                                       \
122                                                                         \
123 /* --- @pre_countersetkey@ --- *                                        \
124  *                                                                      \
125  * Arguments:   @pre_counterctx *ctx@ = pointer to counter context      \
126  *              @const pre_ctx *k@ = pointer to cipher context          \
127  *                                                                      \
128  * Returns:     ---                                                     \
129  *                                                                      \
130  * Use:         Sets the counter context to use a different cipher key. \
131  */                                                                     \
132                                                                         \
133 void pre##_countersetkey(pre##_counterctx *ctx, const pre##_ctx *k)     \
134 {                                                                       \
135   ctx->ctx = *k;                                                        \
136 }                                                                       \
137                                                                         \
138 /* --- @pre_counterinit@ --- *                                          \
139  *                                                                      \
140  * Arguments:   @pre_counterctx *ctx@ = pointer to cipher context       \
141  *              @const void *key@ = pointer to the key buffer           \
142  *              @size_t sz@ = size of the key                           \
143  *              @const void *iv@ = pointer to initialization vector     \
144  *                                                                      \
145  * Returns:     ---                                                     \
146  *                                                                      \
147  * Use:         Initializes a counter context ready for use.  You       \
148  *              should ensure that the IV chosen is unique: reusing an  \
149  *              IV will compromise the security of the entire           \
150  *              plaintext.  This is equivalent to calls to @pre_init@,  \
151  *              @pre_countersetkey@ and @pre_countersetiv@.             \
152  */                                                                     \
153                                                                         \
154 void pre##_counterinit(pre##_counterctx *ctx,                           \
155                        const void *key, size_t sz,                      \
156                        const void *iv)                                  \
157 {                                                                       \
158   static const octet zero[PRE##_BLKSZ] = { 0 };                         \
159   pre##_init(&ctx->ctx, key, sz);                                       \
160   pre##_countersetiv(ctx, iv ? iv : zero);                              \
161 }                                                                       \
162                                                                         \
163 /* --- @pre_counterencrypt@ --- *                                       \
164  *                                                                      \
165  * Arguments:   @pre_counterctx *ctx@ = pointer to counter context      \
166  *              @const void *src@ = pointer to source data              \
167  *              @void *dest@ = pointer to destination data              \
168  *              @size_t sz@ = size of block to be encrypted             \
169  *                                                                      \
170  * Returns:     ---                                                     \
171  *                                                                      \
172  * Use:         Encrypts or decrypts a block with a block cipher in     \
173  *              counter mode: encryption and decryption are the same in \
174  *              counter.  The destination may be null to just churn the \
175  *              feedback round for a bit.  The source may be null to    \
176  *              use the cipher as a random data generator.              \
177  */                                                                     \
178                                                                         \
179 void pre##_counterencrypt(pre##_counterctx *ctx,                        \
180                           const void *src, void *dest,                  \
181                           size_t sz)                                    \
182 {                                                                       \
183   const octet *s = src;                                                 \
184   octet *d = dest;                                                      \
185   unsigned off = ctx->off;                                              \
186                                                                         \
187   /* --- Empty blocks are trivial --- */                                \
188                                                                         \
189   if (!sz)                                                              \
190     return;                                                             \
191                                                                         \
192   /* --- If I can deal with the block from my buffer, do that --- */    \
193                                                                         \
194   if (sz < PRE##_BLKSZ - off)                                           \
195     goto small;                                                         \
196                                                                         \
197   /* --- Finish off what's left in my buffer --- */                     \
198                                                                         \
199   if (!d)                                                               \
200     sz -= PRE##_BLKSZ - off;                                            \
201   else {                                                                \
202     while (off < PRE##_BLKSZ) {                                         \
203       register octet x = s ? *s++ : 0;                                  \
204       *d++ = ctx->buf[off++] ^ x;                                       \
205       sz--;                                                             \
206     }                                                                   \
207   }                                                                     \
208                                                                         \
209   /* --- Main encryption loop --- */                                    \
210                                                                         \
211   {                                                                     \
212     uint32 n[PRE##_BLKSZ / 4];                                          \
213                                                                         \
214     for (;;) {                                                          \
215       pre##_eblk(&ctx->ctx, ctx->n, n);                                 \
216       BLKC_STEP(PRE, ctx->n);                                           \
217       if (sz < PRE##_BLKSZ)                                             \
218         break;                                                          \
219       if (d) {                                                          \
220         if (!s)                                                         \
221           BLKC_STORE(PRE, d, n);                                        \
222         else {                                                          \
223           uint32 x[PRE##_BLKSZ / 4];                                    \
224           BLKC_LOAD(PRE, x, s);                                         \
225           BLKC_XSTORE(PRE, d, n, x);                                    \
226           s += PRE##_BLKSZ;                                             \
227         }                                                               \
228         d += PRE##_BLKSZ;                                               \
229       }                                                                 \
230       sz -= PRE##_BLKSZ;                                                \
231     }                                                                   \
232                                                                         \
233     BLKC_STORE(PRE, ctx->buf, n);                                       \
234     off = 0;                                                            \
235   }                                                                     \
236                                                                         \
237   /* --- Tidying up the tail end --- */                                 \
238                                                                         \
239   if (sz) {                                                             \
240   small:                                                                \
241     if (!d)                                                             \
242       off += sz;                                                        \
243     else do {                                                           \
244       register octet x = s ? *s++ : 0;                                  \
245       *d++ = ctx->buf[off++] ^ x;                                       \
246       sz--;                                                             \
247     } while (sz);                                                       \
248   }                                                                     \
249                                                                         \
250   /* --- Done --- */                                                    \
251                                                                         \
252   ctx->off = off;                                                       \
253   return;                                                               \
254 }                                                                       \
255                                                                         \
256 /* --- Generic cipher interface --- */                                  \
257                                                                         \
258 static const gcipher_ops gops;                                          \
259                                                                         \
260 typedef struct gctx {                                                   \
261   gcipher c;                                                            \
262   pre##_counterctx k;                                                   \
263 } gctx;                                                                 \
264                                                                         \
265 static gcipher *ginit(const void *k, size_t sz)                         \
266 {                                                                       \
267   gctx *g = S_CREATE(gctx);                                             \
268   g->c.ops = &gops;                                                     \
269   pre##_counterinit(&g->k, k, sz, 0);                                   \
270   return (&g->c);                                                       \
271 }                                                                       \
272                                                                         \
273 static void gencrypt(gcipher *c, const void *s, void *t, size_t sz)     \
274 {                                                                       \
275   gctx *g = (gctx *)c;                                                  \
276   pre##_counterencrypt(&g->k, s, t, sz);                                \
277 }                                                                       \
278                                                                         \
279 static void gdestroy(gcipher *c)                                        \
280 {                                                                       \
281   gctx *g = (gctx *)c;                                                  \
282   BURN(*g);                                                             \
283   S_DESTROY(g);                                                         \
284 }                                                                       \
285                                                                         \
286 static void gsetiv(gcipher *c, const void *iv)                          \
287 {                                                                       \
288   gctx *g = (gctx *)c;                                                  \
289   pre##_countersetiv(&g->k, iv);                                        \
290 }                                                                       \
291                                                                         \
292 static void gbdry(gcipher *c)                                           \
293 {                                                                       \
294   gctx *g = (gctx *)c;                                                  \
295   pre##_counterbdry(&g->k);                                             \
296 }                                                                       \
297                                                                         \
298 static const gcipher_ops gops = {                                       \
299   &pre##_counter,                                                       \
300   gencrypt, gencrypt, gdestroy, gsetiv, gbdry                           \
301 };                                                                      \
302                                                                         \
303 const gccipher pre##_counter = {                                        \
304   name "-counter", pre##_keysz, PRE##_BLKSZ,                            \
305   ginit                                                                 \
306 };                                                                      \
307                                                                         \
308 /* --- Generic random number generator interface --- */                 \
309                                                                         \
310 typedef struct grctx {                                                  \
311   grand r;                                                              \
312   pre##_counterctx k;                                                   \
313 } grctx;                                                                \
314                                                                         \
315 static void grdestroy(grand *r)                                         \
316 {                                                                       \
317   grctx *g = (grctx *)r;                                                \
318   BURN(*g);                                                             \
319   S_DESTROY(g);                                                         \
320 }                                                                       \
321                                                                         \
322 static int grmisc(grand *r, unsigned op, ...)                           \
323 {                                                                       \
324   grctx *g = (grctx *)r;                                                \
325   va_list ap;                                                           \
326   int rc = 0;                                                           \
327   octet buf[PRE##_BLKSZ];                                               \
328   va_start(ap, op);                                                     \
329                                                                         \
330   switch (op) {                                                         \
331     case GRAND_CHECK:                                                   \
332       switch (va_arg(ap, unsigned)) {                                   \
333         case GRAND_CHECK:                                               \
334         case GRAND_SEEDINT:                                             \
335         case GRAND_SEEDUINT32:                                          \
336         case GRAND_SEEDBLOCK:                                           \
337         case GRAND_SEEDRAND:                                            \
338           rc = 1;                                                       \
339           break;                                                        \
340         default:                                                        \
341           rc = 0;                                                       \
342           break;                                                        \
343       }                                                                 \
344       break;                                                            \
345     case GRAND_SEEDINT:                                                 \
346       BLKC_SET(PRE, g->k.n, va_arg(ap, unsigned));                      \
347       g->k.off = PRE##_BLKSZ;                                           \
348       break;                                                            \
349     case GRAND_SEEDUINT32:                                              \
350       BLKC_SET(PRE, g->k.n, va_arg(ap, uint32));                        \
351       g->k.off = PRE##_BLKSZ;                                           \
352       break;                                                            \
353     case GRAND_SEEDBLOCK: {                                             \
354       const void *p = va_arg(ap, const void *);                         \
355       size_t sz = va_arg(ap, size_t);                                   \
356       if (sz < sizeof(buf)) {                                           \
357         memset(buf, 0, sizeof(buf));                                    \
358         memcpy(buf, p, sz);                                             \
359         p = buf;                                                        \
360       }                                                                 \
361       pre##_countersetiv(&g->k, p);                                     \
362     } break;                                                            \
363     case GRAND_SEEDRAND: {                                              \
364       grand *rr = va_arg(ap, grand *);                                  \
365       rr->ops->fill(rr, buf, sizeof(buf));                              \
366       pre##_countersetiv(&g->k, buf);                                   \
367     } break;                                                            \
368     default:                                                            \
369       GRAND_BADOP;                                                      \
370       break;                                                            \
371   }                                                                     \
372                                                                         \
373   va_end(ap);                                                           \
374   return (rc);                                                          \
375 }                                                                       \
376                                                                         \
377 static octet grbyte(grand *r)                                           \
378 {                                                                       \
379   grctx *g = (grctx *)r;                                                \
380   octet o;                                                              \
381   pre##_counterencrypt(&g->k, 0, &o, 1);                                \
382   return (o);                                                           \
383 }                                                                       \
384                                                                         \
385 static uint32 grword(grand *r)                                          \
386 {                                                                       \
387   grctx *g = (grctx *)r;                                                \
388   octet b[4];                                                           \
389   pre##_counterencrypt(&g->k, 0, b, sizeof(b));                         \
390   return (LOAD32(b));                                                   \
391 }                                                                       \
392                                                                         \
393 static void grfill(grand *r, void *p, size_t sz)                        \
394 {                                                                       \
395   grctx *g = (grctx *)r;                                                \
396   pre##_counterencrypt(&g->k, 0, p, sz);                                \
397 }                                                                       \
398                                                                         \
399 static const grand_ops grops = {                                        \
400   name "-counter",                                                      \
401   GRAND_CRYPTO, 0,                                                      \
402   grmisc, grdestroy,                                                    \
403   grword, grbyte, grword, grand_defaultrange, grfill                    \
404 };                                                                      \
405                                                                         \
406 /* --- @pre_counterrand@ --- *                                          \
407  *                                                                      \
408  * Arguments:   @const void *k@ = pointer to key material               \
409  *              @size_t sz@ = size of key material                      \
410  *                                                                      \
411  * Returns:     Pointer to generic random number generator interface.   \
412  *                                                                      \
413  * Use:         Creates a random number interface wrapper around an     \
414  *              counter-mode block cipher.                              \
415  */                                                                     \
416                                                                         \
417 grand *pre##_counterrand(const void *k, size_t sz)                      \
418 {                                                                       \
419   grctx *g = S_CREATE(grctx);                                           \
420   g->r.ops = &grops;                                                    \
421   pre##_counterinit(&g->k, k, sz, 0);                                   \
422   return (&g->r);                                                       \
423 }                                                                       \
424                                                                         \
425 COUNTER_TESTX(PRE, pre, name, fname)
426
427 /*----- Test rig ----------------------------------------------------------*/
428
429 #define COUNTER_TEST(PRE, pre) COUNTER_TESTX(PRE, pre, #pre, #pre)
430
431 #ifdef TEST_RIG
432
433 #include <stdio.h>
434
435 #include "daftstory.h"
436
437 /* --- @COUNTER_TEST@ --- *
438  *
439  * Arguments:   @PRE@, @pre@ = prefixes for block cipher definitions
440  *
441  * Use:         Standard test rig for counter functions.
442  */
443
444 #define COUNTER_TESTX(PRE, pre, name, fname)                            \
445                                                                         \
446 /* --- Initial plaintext for the test --- */                            \
447                                                                         \
448 static const octet text[] = TEXT;                                       \
449                                                                         \
450 /* --- Key and IV to use --- */                                         \
451                                                                         \
452 static const octet key[] = KEY;                                         \
453 static const octet iv[] = IV;                                           \
454                                                                         \
455 /* --- Buffers for encryption and decryption output --- */              \
456                                                                         \
457 static octet ct[sizeof(text)];                                          \
458 static octet pt[sizeof(text)];                                          \
459                                                                         \
460 static void hexdump(const octet *p, size_t sz, size_t off)              \
461 {                                                                       \
462   const octet *q = p + sz;                                              \
463   for (sz = 0; p < q; p++, sz++) {                                      \
464     printf("%02x", *p);                                                 \
465     if ((off + sz + 1) % PRE##_BLKSZ == 0)                              \
466       putchar(':');                                                     \
467   }                                                                     \
468 }                                                                       \
469                                                                         \
470 int main(void)                                                          \
471 {                                                                       \
472   size_t sz = 0, rest;                                                  \
473   pre##_counterctx ctx;                                                 \
474   int status = 0;                                                       \
475   int done = 0;                                                         \
476   pre##_ctx k;                                                          \
477                                                                         \
478   size_t keysz = PRE##_KEYSZ ?                                          \
479     PRE##_KEYSZ : strlen((const char *)key);                            \
480                                                                         \
481   fputs(name "-counter: ", stdout);                                     \
482                                                                         \
483   pre##_init(&k, key, keysz);                                           \
484   pre##_countersetkey(&ctx, &k);                                        \
485                                                                         \
486   while (sz <= sizeof(text)) {                                          \
487     rest = sizeof(text) - sz;                                           \
488     memcpy(ct, text, sizeof(text));                                     \
489     pre##_countersetiv(&ctx, iv);                                       \
490     pre##_counterencrypt(&ctx, ct, ct, sz);                             \
491     pre##_counterencrypt(&ctx, ct + sz, ct + sz, rest);                 \
492     memcpy(pt, ct, sizeof(text));                                       \
493     pre##_countersetiv(&ctx, iv);                                       \
494     pre##_counterencrypt(&ctx, pt, pt, rest);                           \
495     pre##_counterencrypt(&ctx, pt + rest, pt + rest, sz);               \
496     if (memcmp(pt, text, sizeof(text)) == 0) {                          \
497       done++;                                                           \
498       if (sizeof(text) < 40 || done % 8 == 0)                           \
499         fputc('.', stdout);                                             \
500       if (done % 480 == 0)                                              \
501         fputs("\n\t", stdout);                                          \
502       fflush(stdout);                                                   \
503     } else {                                                            \
504       printf("\nError (sz = %lu)\n", (unsigned long)sz);                \
505       status = 1;                                                       \
506       printf("\tplaintext      = "); hexdump(text, sz, 0);              \
507         printf(", "); hexdump(text + sz, rest, sz);                     \
508         fputc('\n', stdout);                                            \
509       printf("\tciphertext     = "); hexdump(ct, sz, 0);                \
510         printf(", "); hexdump(ct + sz, rest, sz);                       \
511         fputc('\n', stdout);                                            \
512       printf("\trecovered text = "); hexdump(pt, sz, 0);                \
513         printf(", "); hexdump(pt + sz, rest, sz);                       \
514         fputc('\n', stdout);                                            \
515       fputc('\n', stdout);                                              \
516     }                                                                   \
517     if (sz < 63)                                                        \
518       sz++;                                                             \
519     else                                                                \
520       sz += 9;                                                          \
521   }                                                                     \
522                                                                         \
523   fputs(status ? " failed\n" : " ok\n", stdout);                        \
524   return (status);                                                      \
525 }
526
527 #else
528 #  define COUNTER_TESTX(PRE, pre, name, fname)
529 #endif
530
531 /*----- That's all, folks -------------------------------------------------*/
532
533 #ifdef __cplusplus
534   }
535 #endif
536
537 #endif