catcrypt: Implement symmetric key-encapsulation and signature schemes.
[u/mdw/catacomb] / cc-kem.c
index b6908e5..1766c8e 100644 (file)
--- a/cc-kem.c
+++ b/cc-kem.c
@@ -350,6 +350,67 @@ static const kemops ec_decops = {
   ec_decinit, dh_decdoit, dh_enccheck, dh_encdestroy
 };
 
+/* --- Symmetric --- */
+
+typedef struct symm_ctx {
+  kem k;
+  key_packdef kp;
+  key_bin kb;
+} symm_ctx;
+
+static kem *symm_init(key *k, void *kd)
+{
+  symm_ctx *s;
+  dstr d = DSTR_INIT;
+  int err;
+
+  s = CREATE(symm_ctx);
+
+  key_fulltag(k, &d);
+  s->kp.e = KENC_BINARY;
+  s->kp.p = &s->kb;
+  s->kp.kd = 0;
+
+  if ((err = key_unpack(&s->kp, kd, &d)) != 0) {
+    die(EXIT_FAILURE, "failed to unpack symmetric key `%s': %s",
+       d.buf, key_strerror(err));
+  }
+  dstr_destroy(&d);
+  return (&s->k);
+}
+
+static int symm_decdoit(kem *k, dstr *d, ghash *h)
+{
+  symm_ctx *s = (symm_ctx *)k;
+
+  GH_HASH(h, s->kb.k, s->kb.sz);
+  GH_HASH(h, d->buf, d->len);
+  return (0);
+}
+
+static int symm_encdoit(kem *k, dstr *d, ghash *h)
+{
+  dstr_ensure(d, h->ops->c->hashsz);
+  d->len += h->ops->c->hashsz;
+  rand_get(RAND_GLOBAL, d->buf, d->len);
+  return (symm_decdoit(k, d, h));
+}
+
+static const char *symm_check(kem *k) { return (0); }
+
+static void symm_destroy(kem *k)
+  { symm_ctx *s = (symm_ctx *)k; key_unpackdone(&s->kp); }
+
+static const kemops symm_encops = {
+  0, 0,
+  symm_init, symm_encdoit, symm_check, symm_destroy
+};
+
+static const kemops symm_decops = {
+  0, 0,
+  symm_init, symm_decdoit, symm_check, symm_destroy
+};
+
 /* --- The switch table --- */
 
 const struct kemtab kemtab[] = {
@@ -357,6 +418,7 @@ const struct kemtab kemtab[] = {
   { "dh",      &dh_encops,     &dh_decops },
   { "bindh",   &bindh_encops,  &bindh_decops },
   { "ec",      &ec_encops,     &ec_decops },
+  { "symm",    &symm_encops,   &symm_decops },
   { 0,         0,              0 }
 };
 
@@ -437,10 +499,17 @@ kem *getkem(key *k, const char *app, int wantpriv)
       kalg, t.buf);
 k_found:;
   ko = wantpriv ? kt->decops : kt->encops;
-  kd = xmalloc(ko->kdsz);
-  kp = key_fetchinit(ko->kf, 0, kd);
-  if ((e = key_fetch(kp, k)) != 0)
-    die(EXIT_FAILURE, "error fetching key `%s': %s", t.buf, key_strerror(e));
+  if (!ko->kf) {
+    kd = k->k;
+    key_incref(kd);
+  } else {
+    kd = xmalloc(ko->kdsz);
+    kp = key_fetchinit(ko->kf, 0, kd);
+    if ((e = key_fetch(kp, k)) != 0) {
+      die(EXIT_FAILURE, "error fetching key `%s': %s",
+         t.buf, key_strerror(e));
+    }
+  }
   kk = ko->init(k, kd);
   kk->kp = kp;
   kk->ops = ko;
@@ -545,8 +614,12 @@ done:
 
 void freekem(kem *k)
 {
-  key_fetchdone(k->kp);
-  xfree(k->kd);
+  if (!k->ops->kf)
+    key_drop(k->kd);
+  else {
+    key_fetchdone(k->kp);
+    xfree(k->kd);
+  }
   k->ops->destroy(k);
 }