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