chiark / gitweb /
Release 2.4.4.
[catacomb] / symm / rc4.c
1 /* -*-c-*-
2  *
3  * The alleged RC4 stream cipher
4  *
5  * (c) 1999 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Catacomb.
11  *
12  * Catacomb is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU Library General Public License as
14  * published by the Free Software Foundation; either version 2 of the
15  * License, or (at your option) any later version.
16  *
17  * Catacomb is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License along with Catacomb; if not, write to the Free
24  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25  * MA 02111-1307, USA.
26  */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #include <assert.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33
34 #include <mLib/bits.h>
35 #include <mLib/sub.h>
36
37 #include "arena.h"
38 #include "gcipher.h"
39 #include "grand.h"
40 #include "paranoia.h"
41 #include "rc4.h"
42
43 /*----- Global variables --------------------------------------------------*/
44
45 const octet rc4_keysz[] = { KSZ_RANGE, RC4_KEYSZ, 1, 255, 1 };
46
47 /*----- Main code ---------------------------------------------------------*/
48
49 /* --- @rc4_addkey@ --- *
50  *
51  * Arguments:   @rc4_ctx *ctx@ = pointer to context to key
52  *              @const void *k@ = pointer to key data to use
53  *              @size_t sz@ = size of the key data
54  *
55  * Returns:     ---
56  *
57  * Use:         Mixes key data with an RC4 context.  The RC4 context is not
58  *              reset before mixing.  This may be used to mix new key
59  *              material with an existing RC4 context.
60  */
61
62 void rc4_addkey(rc4_ctx *ctx, const void *k, size_t sz)
63 {
64   unsigned i, j;
65   const octet *p = k, *q = p + sz;
66
67   KSZ_ASSERT(rc4, sz);
68
69   for (i = j = 0; i < 256; i++) {
70     unsigned si = ctx->s[i];
71     j = (j + si + *p++) & 0xff;
72     ctx->s[i] = ctx->s[j];
73     ctx->s[j] = si;
74     if (p == q)
75       p = k;
76   }
77
78   ctx->i = ctx->j = 0;
79 }
80
81 /* --- @rc4_init@ --- *
82  *
83  * Arguments:   @rc4_ctx *ctx@ = pointer to context to initialize
84  *              @const void *k@ = pointer to key data to use
85  *              @size_t sz@ = size of the key data
86  *
87  * Returns:     ---
88  *
89  * Use:         Initializes an RC4 context ready for use.
90  */
91
92 void rc4_init(rc4_ctx *ctx, const void *k, size_t sz)
93 {
94   unsigned i;
95
96   for (i = 0; i < 256; i++)
97     ctx->s[i] = i;
98   ctx->f = 0;
99   rc4_addkey(ctx, k, sz);
100 }
101
102 /* --- @rc4_encrypt@ --- *
103  *
104  * Arguments:   @rc4_ctx *ctx@ = pointer to context to use
105  *              @const void *src@ = pointer to the source block
106  *              @void *dest@ = pointer to the destination block
107  *              @size_t sz@ = size of the block
108  *
109  * Returns:     ---
110  *
111  * Use:         Encrypts or decrypts a block of data.  The destination may
112  *              be null to just grind the generator around for a while.  It's
113  *              recommended that you say `@rc4_encrypt(&ctx, 0, 0, 1024)@'
114  *              after initializing a new context, to prevent keystream
115  *              guessing attacks.  The source may be null to just extract a
116  *              big lump of data from the generator.
117  */
118
119 void rc4_encrypt(rc4_ctx *ctx, const void *src, void *dest, size_t sz)
120 {
121   const octet *s = src;
122   octet *d = dest;
123
124   if (!d)
125     RC4_OPEN(ctx, while (sz) { unsigned x; RC4_BYTE(x); (void)x; sz--; });
126   else if (!s)
127     RC4_OPEN(ctx, while (sz) { RC4_BYTE(*d++); sz--; });
128   else
129     RC4_OPEN(ctx,
130              while (sz) { unsigned x; RC4_BYTE(x); *d++ = *s++ ^ x; sz--; });
131 }
132
133 /*----- Generic cipher interface ------------------------------------------*/
134
135 typedef struct gctx {
136   gcipher c;
137   rc4_ctx rc4;
138 } gctx;
139
140 static const gcipher_ops gops;
141
142 static gcipher *ginit(const void *k, size_t sz)
143 {
144   gctx *g = S_CREATE(gctx);
145   g->c.ops = &gops;
146   rc4_init(&g->rc4, k, sz);
147   return (&g->c);
148 }
149
150 static void gencrypt(gcipher *c, const void *s, void *t, size_t sz)
151 {
152   gctx *g = (gctx *)c;
153   rc4_encrypt(&g->rc4, s, t, sz);
154 }
155
156 static void gdestroy(gcipher *c)
157 {
158   gctx *g = (gctx *)c;
159   BURN(*g);
160   S_DESTROY(g);
161 }
162
163 static const gcipher_ops gops = {
164   &rc4,
165   gencrypt, gencrypt, gdestroy, 0, 0
166 };
167
168 const gccipher rc4 = {
169   "rc4", rc4_keysz, 0,
170   ginit
171 };
172
173 /*----- Generic random number generator interface -------------------------*/
174
175 typedef struct grctx {
176   grand r;
177   rc4_ctx rc4;
178 } grctx;
179
180 static void grdestroy(grand *r)
181 {
182   grctx *g = (grctx *)r;
183   BURN(*g);
184   S_DESTROY(g);
185 }
186
187 static int grmisc(grand *r, unsigned op, ...)
188 {
189   grctx *g = (grctx *)r;
190   va_list ap;
191   int rc = 0;
192   uint32 i;
193   octet buf[4];
194   va_start(ap, op);
195
196   switch (op) {
197     case GRAND_CHECK:
198       switch (va_arg(ap, unsigned)) {
199         case GRAND_CHECK:
200         case GRAND_SEEDINT:
201         case GRAND_SEEDUINT32:
202         case GRAND_SEEDBLOCK:
203         case GRAND_SEEDRAND:
204           rc = 1;
205           break;
206         default:
207           rc = 0;
208           break;
209       }
210       break;
211     case GRAND_SEEDINT:
212       i = va_arg(ap, unsigned);
213       STORE32(buf, i);
214       rc4_addkey(&g->rc4, buf, sizeof(buf));
215       break;
216     case GRAND_SEEDUINT32:
217       i = va_arg(ap, uint32);
218       STORE32(buf, i);
219       rc4_addkey(&g->rc4, buf, sizeof(buf));
220       break;
221     case GRAND_SEEDBLOCK: {
222       const void *p = va_arg(ap, const void *);
223       size_t sz = va_arg(ap, size_t);
224       rc4_addkey(&g->rc4, p, sz);
225     } break;
226     case GRAND_SEEDRAND: {
227       grand *rr = va_arg(ap, grand *);
228       octet buf[16];
229       rr->ops->fill(rr, buf, sizeof(buf));
230       rc4_addkey(&g->rc4, buf, sizeof(buf));
231     } break;
232     default:
233       GRAND_BADOP;
234       break;
235   }
236
237   va_end(ap);
238   return (rc);
239 }
240
241 static octet grbyte(grand *r)
242 {
243   grctx *g = (grctx *)r;
244   octet o;
245   RC4_OPEN(&g->rc4, RC4_BYTE(o););
246   return (o);
247 }
248
249 static uint32 grword(grand *r)
250 {
251   grctx *g = (grctx *)r;
252   octet b[4];
253   int i;
254   RC4_OPEN(&g->rc4,
255            for (i = 0; i < sizeof(b); i++)
256              RC4_BYTE(b[i]););
257   return (LOAD32(b));
258 }
259
260 static void grfill(grand *r, void *p, size_t sz)
261 {
262   grctx *g = (grctx *)r;
263   rc4_encrypt(&g->rc4, 0, p, sz);
264 }
265
266 static const grand_ops grops = {
267   "rc4",
268   GRAND_CRYPTO, 0,
269   grmisc, grdestroy,
270   grword, grbyte, grword, grand_defaultrange, grfill
271 };
272
273 /* --- @rc4_rand@ --- *
274  *
275  * Arguments:   @const void *k@ = pointer to key material
276  *              @size_t sz@ = size of key material
277  *
278  * Returns:     Pointer to generic random number generator interface.
279  *
280  * Use:         Creates a random number interface wrapper around the RC4
281  *              stream cipher.
282  */
283
284 grand *rc4_rand(const void *k, size_t sz)
285 {
286   grctx *g = S_CREATE(grctx);
287   g->r.ops = &grops;
288   rc4_init(&g->rc4, k, sz);
289   return (&g->r);
290 }
291
292 /*----- Test rig ----------------------------------------------------------*/
293
294 #ifdef TEST_RIG
295
296 #include <stdio.h>
297 #include <string.h>
298
299 #include <mLib/quis.h>
300 #include <mLib/testrig.h>
301
302 static int v_encrypt(dstr *v)
303 {
304   rc4_ctx ctx;
305   dstr d = DSTR_INIT;
306   int ok = 1;
307
308   rc4_init(&ctx, v[0].buf, v[0].len);
309   dstr_ensure(&d, v[1].len);
310   d.len = v[1].len;
311   rc4_encrypt(&ctx, v[1].buf, d.buf, d.len);
312
313   if (memcmp(v[2].buf, d.buf, d.len) != 0) {
314     ok = 0;
315     printf("\nfail encryption:"
316            "\n\tkey        = ");
317     type_hex.dump(&v[0], stdout);
318     printf("\n\tplaintext  = "); type_hex.dump(&v[1], stdout);
319     printf("\n\texpected   = "); type_hex.dump(&v[2], stdout);
320     printf("\n\tcalculated = "); type_hex.dump(&d, stdout);
321     putchar('\n');
322   }
323
324   return (ok);
325 }
326
327 static int v_generate(dstr *v)
328 {
329   rc4_ctx ctx;
330   dstr d = DSTR_INIT;
331   int ok = 1;
332
333   rc4_init(&ctx, v[0].buf, v[0].len);
334   rc4_encrypt(&ctx, 0, 0, *(int *)v[1].buf);
335   dstr_ensure(&d, v[2].len);
336   d.len = v[2].len;
337   rc4_encrypt(&ctx, 0, d.buf, d.len);
338
339   if (memcmp(v[2].buf, d.buf, d.len) != 0) {
340     ok = 0;
341     printf("\nfail generation:"
342            "\n\tkey        = ");
343     type_hex.dump(&v[0], stdout);
344     printf("\n\tskip len   = %i", *(int *)v[1].buf);
345     printf("\n\texpected   = "); type_hex.dump(&v[2], stdout);
346     printf("\n\tcalculated = "); type_hex.dump(&d, stdout);
347     putchar('\n');
348   }
349
350   return (ok);
351 }
352
353 static test_chunk defs[] = {
354   { "rc4-encrypt", v_encrypt, { &type_hex, &type_hex, &type_hex, 0 } },
355   { "rc4-generate", v_generate, { &type_hex, &type_int, &type_hex, 0 } },
356   { 0, 0, { 0 } }
357 };
358
359 int main(int argc, char *argv[])
360 {
361   test_run(argc, argv, defs, SRCDIR"/t/rc4");
362   return (0);
363 }
364
365 #endif
366
367 /*----- That's all, folks -------------------------------------------------*/