Rearrange the file tree.
[u/mdw/catacomb] / symm / rc4.c
diff --git a/symm/rc4.c b/symm/rc4.c
new file mode 100644 (file)
index 0000000..0d02062
--- /dev/null
@@ -0,0 +1,367 @@
+/* -*-c-*-
+ *
+ * The alleged RC4 stream cipher
+ *
+ * (c) 1999 Straylight/Edgeware
+ */
+
+/*----- Licensing notice --------------------------------------------------*
+ *
+ * This file is part of Catacomb.
+ *
+ * Catacomb is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Library General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * Catacomb is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with Catacomb; if not, write to the Free
+ * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
+ * MA 02111-1307, USA.
+ */
+
+/*----- Header files ------------------------------------------------------*/
+
+#include <assert.h>
+#include <stdarg.h>
+#include <stdio.h>
+
+#include <mLib/bits.h>
+#include <mLib/sub.h>
+
+#include "arena.h"
+#include "gcipher.h"
+#include "grand.h"
+#include "paranoia.h"
+#include "rc4.h"
+
+/*----- Global variables --------------------------------------------------*/
+
+const octet rc4_keysz[] = { KSZ_RANGE, RC4_KEYSZ, 1, 255, 1 };
+
+/*----- Main code ---------------------------------------------------------*/
+
+/* --- @rc4_addkey@ --- *
+ *
+ * Arguments:  @rc4_ctx *ctx@ = pointer to context to key
+ *             @const void *k@ = pointer to key data to use
+ *             @size_t sz@ = size of the key data
+ *
+ * Returns:    ---
+ *
+ * Use:                Mixes key data with an RC4 context.  The RC4 context is not
+ *             reset before mixing.  This may be used to mix new key
+ *             material with an existing RC4 context.
+ */
+
+void rc4_addkey(rc4_ctx *ctx, const void *k, size_t sz)
+{
+  unsigned i, j;
+  const octet *p = k, *q = p + sz;
+
+  KSZ_ASSERT(rc4, sz);
+
+  for (i = j = 0; i < 256; i++) {
+    unsigned si = ctx->s[i];
+    j = (j + si + *p++) & 0xff;
+    ctx->s[i] = ctx->s[j];
+    ctx->s[j] = si;
+    if (p == q)
+      p = k;
+  }
+
+  ctx->i = ctx->j = 0;
+}
+
+/* --- @rc4_init@ --- *
+ *
+ * Arguments:  @rc4_ctx *ctx@ = pointer to context to initialize
+ *             @const void *k@ = pointer to key data to use
+ *             @size_t sz@ = size of the key data
+ *
+ * Returns:    ---
+ *
+ * Use:                Initializes an RC4 context ready for use.
+ */
+
+void rc4_init(rc4_ctx *ctx, const void *k, size_t sz)
+{
+  unsigned i;
+
+  for (i = 0; i < 256; i++)
+    ctx->s[i] = i;
+  ctx->f = 0;
+  rc4_addkey(ctx, k, sz);
+}
+
+/* --- @rc4_encrypt@ --- *
+ *
+ * Arguments:  @rc4_ctx *ctx@ = pointer to context to use
+ *             @const void *src@ = pointer to the source block
+ *             @void *dest@ = pointer to the destination block
+ *             @size_t sz@ = size of the block
+ *
+ * Returns:    ---
+ *
+ * Use:                Encrypts or decrypts a block of data.  The destination may
+ *             be null to just grind the generator around for a while.  It's
+ *             recommended that you say `@rc4_encrypt(&ctx, 0, 0, 1024)@'
+ *             after initializing a new context, to prevent keystream
+ *             guessing attacks.  The source may be null to just extract a
+ *             big lump of data from the generator.
+ */
+
+void rc4_encrypt(rc4_ctx *ctx, const void *src, void *dest, size_t sz)
+{
+  const octet *s = src;
+  octet *d = dest;
+
+  if (!d)
+    RC4_OPEN(ctx, while (sz) { unsigned x; RC4_BYTE(x); sz--; });
+  else if (!s)
+    RC4_OPEN(ctx, while (sz) { RC4_BYTE(*d++); sz--; });
+  else
+    RC4_OPEN(ctx,
+            while (sz) { unsigned x; RC4_BYTE(x); *d++ = *s++ ^ x; sz--; });
+}
+
+/*----- Generic cipher interface ------------------------------------------*/
+
+typedef struct gctx {
+  gcipher c;
+  rc4_ctx rc4;
+} gctx;
+
+static const gcipher_ops gops;
+
+static gcipher *ginit(const void *k, size_t sz)
+{
+  gctx *g = S_CREATE(gctx);
+  g->c.ops = &gops;
+  rc4_init(&g->rc4, k, sz);
+  return (&g->c);
+}
+
+static void gencrypt(gcipher *c, const void *s, void *t, size_t sz)
+{
+  gctx *g = (gctx *)c;
+  rc4_encrypt(&g->rc4, s, t, sz);
+}
+
+static void gdestroy(gcipher *c)
+{
+  gctx *g = (gctx *)c;
+  BURN(*g);
+  S_DESTROY(g);
+}
+
+static const gcipher_ops gops = {
+  &rc4,
+  gencrypt, gencrypt, gdestroy, 0, 0
+};
+
+const gccipher rc4 = {
+  "rc4", rc4_keysz, 0,
+  ginit
+};
+
+/*----- Generic random number generator interface -------------------------*/
+
+typedef struct grctx {
+  grand r;
+  rc4_ctx rc4;
+} grctx;
+
+static void grdestroy(grand *r)
+{
+  grctx *g = (grctx *)r;
+  BURN(*g);
+  S_DESTROY(g);
+}
+
+static int grmisc(grand *r, unsigned op, ...)
+{
+  grctx *g = (grctx *)r;
+  va_list ap;
+  int rc = 0;
+  uint32 i;
+  octet buf[4];
+  va_start(ap, op);
+
+  switch (op) {
+    case GRAND_CHECK:
+      switch (va_arg(ap, unsigned)) {
+       case GRAND_CHECK:
+       case GRAND_SEEDINT:
+       case GRAND_SEEDUINT32:
+       case GRAND_SEEDBLOCK:
+       case GRAND_SEEDRAND:
+         rc = 1;
+         break;
+       default:
+         rc = 0;
+         break;
+      }
+      break;
+    case GRAND_SEEDINT:
+      i = va_arg(ap, unsigned);
+      STORE32(buf, i);
+      rc4_addkey(&g->rc4, buf, sizeof(buf));
+      break;
+    case GRAND_SEEDUINT32:
+      i = va_arg(ap, uint32);
+      STORE32(buf, i);
+      rc4_addkey(&g->rc4, buf, sizeof(buf));
+      break;
+    case GRAND_SEEDBLOCK: {
+      const void *p = va_arg(ap, const void *);
+      size_t sz = va_arg(ap, size_t);
+      rc4_addkey(&g->rc4, p, sz);
+    } break;
+    case GRAND_SEEDRAND: {
+      grand *rr = va_arg(ap, grand *);
+      octet buf[16];
+      rr->ops->fill(rr, buf, sizeof(buf));
+      rc4_addkey(&g->rc4, buf, sizeof(buf));
+    } break;
+    default:
+      GRAND_BADOP;
+      break;
+  }
+
+  va_end(ap);
+  return (rc);
+}
+
+static octet grbyte(grand *r)
+{
+  grctx *g = (grctx *)r;
+  octet o;
+  RC4_OPEN(&g->rc4, RC4_BYTE(o););
+  return (o);
+}
+
+static uint32 grword(grand *r)
+{
+  grctx *g = (grctx *)r;
+  octet b[4];
+  int i;
+  RC4_OPEN(&g->rc4,
+          for (i = 0; i < sizeof(b); i++)
+            RC4_BYTE(b[i]););
+  return (LOAD32(b));
+}
+
+static void grfill(grand *r, void *p, size_t sz)
+{
+  grctx *g = (grctx *)r;
+  rc4_encrypt(&g->rc4, 0, p, sz);
+}
+
+static const grand_ops grops = {
+  "rc4",
+  GRAND_CRYPTO, 0,
+  grmisc, grdestroy,
+  grword, grbyte, grword, grand_range, grfill
+};
+
+/* --- @rc4_rand@ --- *
+ *
+ * Arguments:  @const void *k@ = pointer to key material
+ *             @size_t sz@ = size of key material
+ *
+ * Returns:    Pointer to generic random number generator interface.
+ *
+ * Use:                Creates a random number interface wrapper around an
+ *             OFB-mode block cipher.
+ */
+
+grand *rc4_rand(const void *k, size_t sz)
+{
+  grctx *g = S_CREATE(grctx);
+  g->r.ops = &grops;
+  rc4_init(&g->rc4, k, sz);
+  return (&g->r);
+}
+
+/*----- Test rig ----------------------------------------------------------*/
+
+#ifdef TEST_RIG
+
+#include <stdio.h>
+#include <string.h>
+
+#include <mLib/quis.h>
+#include <mLib/testrig.h>
+
+static int v_encrypt(dstr *v)
+{
+  rc4_ctx ctx;
+  dstr d = DSTR_INIT;
+  int ok = 1;
+
+  rc4_init(&ctx, v[0].buf, v[0].len);
+  dstr_ensure(&d, v[1].len);
+  d.len = v[1].len;
+  rc4_encrypt(&ctx, v[1].buf, d.buf, d.len);
+
+  if (memcmp(v[2].buf, d.buf, d.len) != 0) {
+    ok = 0;
+    printf("\nfail encryption:"
+          "\n\tkey        = ");
+    type_hex.dump(&v[0], stdout);
+    printf("\n\tplaintext  = "); type_hex.dump(&v[1], stdout);
+    printf("\n\texpected   = "); type_hex.dump(&v[2], stdout);
+    printf("\n\tcalculated = "); type_hex.dump(&d, stdout);
+    putchar('\n');
+  }
+
+  return (ok);
+}
+
+static int v_generate(dstr *v)
+{
+  rc4_ctx ctx;
+  dstr d = DSTR_INIT;
+  int ok = 1;
+
+  rc4_init(&ctx, v[0].buf, v[0].len);
+  rc4_encrypt(&ctx, 0, 0, *(int *)v[1].buf);
+  dstr_ensure(&d, v[2].len);
+  d.len = v[2].len;
+  rc4_encrypt(&ctx, 0, d.buf, d.len);
+
+  if (memcmp(v[2].buf, d.buf, d.len) != 0) {
+    ok = 0;
+    printf("\nfail generation:"
+          "\n\tkey        = ");
+    type_hex.dump(&v[0], stdout);
+    printf("\n\tskip len   = %i", *(int *)v[1].buf);
+    printf("\n\texpected   = "); type_hex.dump(&v[2], stdout);
+    printf("\n\tcalculated = "); type_hex.dump(&d, stdout);
+    putchar('\n');
+  }
+
+  return (ok);
+}
+
+static test_chunk defs[] = {
+  { "rc4-encrypt", v_encrypt, { &type_hex, &type_hex, &type_hex, 0 } },
+  { "rc4-generate", v_generate, { &type_hex, &type_int, &type_hex, 0 } },
+  { 0, 0, { 0 } }
+};
+
+int main(int argc, char *argv[])
+{
+  test_run(argc, argv, defs, SRCDIR"/t/rc4");
+  return (0);
+}
+
+#endif
+
+/*----- That's all, folks -------------------------------------------------*/