chiark / gitweb /
progs/cc-kem.c: Add `naclbox' crypto transform.
[catacomb] / progs / cc-kem.c
1 /* -*-c-*-
2  *
3  * Catcrypt key-encapsulation
4  *
5  * (c) 2004 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 #define _FILE_OFFSET_BITS 64
31
32 #include <stdlib.h>
33
34 #include <mLib/alloc.h>
35 #include <mLib/dstr.h>
36 #include <mLib/report.h>
37 #include <mLib/sub.h>
38
39 #include "mprand.h"
40 #include "rand.h"
41
42 #include "ec.h"
43 #include "ec-keys.h"
44 #include "dh.h"
45 #include "rsa.h"
46
47 #include "rmd160.h"
48 #include "blowfish-cbc.h"
49 #include "poly1305.h"
50 #include "salsa20.h"
51 #include "chacha.h"
52
53 #include "cc.h"
54
55 /*----- Bulk crypto -------------------------------------------------------*/
56
57 /* --- NaCl `secretbox' --- */
58
59 typedef struct naclbox_encctx {
60   bulk b;
61   const gccipher *cc;
62   gcipher *c;
63 } naclbox_encctx;
64
65 static bulk *naclbox_init(key *k, const char *calg, const char *halg)
66 {
67   naclbox_encctx *ctx = CREATE(naclbox_encctx);
68   dstr t = DSTR_INIT;
69   const char *q;
70
71   key_fulltag(k, &t);
72
73   if ((q = key_getattr(0, k, "cipher")) != 0) calg = q;
74   if (!calg || strcmp(calg, "salsa20") == 0) ctx->cc = &salsa20;
75   else if (strcmp(calg, "salsa20/12") == 0) ctx->cc = &salsa2012;
76   else if (strcmp(calg, "salsa20/8") == 0) ctx->cc = &salsa208;
77   else if (strcmp(calg, "chacha20") == 0) ctx->cc = &chacha20;
78   else if (strcmp(calg, "chacha12") == 0) ctx->cc = &chacha12;
79   else if (strcmp(calg, "chacha8") == 0) ctx->cc = &chacha8;
80   else {
81     die(EXIT_FAILURE,
82         "unknown or inappropriate encryption scheme `%s' in key `%s'",
83         calg, t.buf);
84   }
85
86   dstr_destroy(&t);
87   return (&ctx->b);
88 }
89
90 static int naclbox_setup(bulk *b, gcipher *cx)
91 {
92   naclbox_encctx *ctx = (naclbox_encctx *)b;
93   octet k[SALSA20_KEYSZ];
94
95   GC_ENCRYPT(cx, 0, k, sizeof(k));
96   ctx->c = GC_INIT(ctx->cc, k, sizeof(k));
97   return (0);
98 }
99
100 static size_t naclbox_overhead(bulk *b) { return (POLY1305_TAGSZ); }
101
102 static void naclbox_destroy(bulk *b)
103 {
104   naclbox_encctx *ctx = (naclbox_encctx *)b;
105
106   GC_DESTROY(ctx->c);
107   DESTROY(ctx);
108 }
109
110 static const char *naclbox_encdoit(bulk *b, uint32 seq, buf *bb,
111                                    const void *p, size_t sz)
112 {
113   naclbox_encctx *ctx = (naclbox_encctx *)b;
114   octet t[32];
115   poly1305_key ak;
116   poly1305_ctx a;
117   octet *tag, *ct;
118
119   STORE32(t, seq); STORE32(t + 4, 0); GC_SETIV(ctx->c, t);
120   GC_ENCRYPT(ctx->c, 0, t, POLY1305_KEYSZ + POLY1305_MASKSZ);
121   poly1305_keyinit(&ak, t, POLY1305_KEYSZ);
122   poly1305_macinit(&a, &ak, t + POLY1305_KEYSZ);
123
124   tag = buf_get(bb, POLY1305_TAGSZ); assert(tag);
125   ct = buf_get(bb, sz); assert(ct);
126   GC_ENCRYPT(ctx->c, p, ct, sz);
127   poly1305_hash(&a, ct, sz);
128   poly1305_done(&a, tag);
129   return (0);
130 }
131
132 static const char *naclbox_decdoit(bulk *b, uint32 seq, buf *bb,
133                                    const void *p, size_t sz)
134 {
135   naclbox_encctx *ctx = (naclbox_encctx *)b;
136   buf bin;
137   octet t[32];
138   poly1305_key ak;
139   poly1305_ctx a;
140   octet *tag, *ct, *pt;
141
142   STORE32(t, seq); STORE32(t + 4, 0); GC_SETIV(ctx->c, t);
143   GC_ENCRYPT(ctx->c, 0, t, POLY1305_KEYSZ + POLY1305_MASKSZ);
144   poly1305_keyinit(&ak, t, POLY1305_KEYSZ);
145   poly1305_macinit(&a, &ak, t + POLY1305_KEYSZ);
146
147   buf_init(&bin, (/*unconst*/ void *)p, sz);
148   if ((tag = buf_get(&bin, POLY1305_TAGSZ)) == 0) return ("no tag");
149   ct = BCUR(&bin); sz = BLEFT(&bin);
150   poly1305_hash(&a, ct, sz);
151   poly1305_done(&a, t);
152   if (!ct_memeq(t, tag, POLY1305_TAGSZ)) return ("authentication failure");
153   pt = buf_get(bb, sz); assert(pt);
154   GC_DECRYPT(ctx->c, ct, pt, sz);
155   return (0);
156 }
157
158 static const bulkops naclbox_encops = {
159   naclbox_init, naclbox_setup, naclbox_overhead,
160   naclbox_encdoit, naclbox_destroy
161 }, naclbox_decops = {
162   naclbox_init, naclbox_setup, naclbox_overhead,
163   naclbox_decdoit, naclbox_destroy
164 };
165
166 /* --- Generic composition --- */
167
168 typedef struct gencomp_encctx {
169   bulk b;
170   const gccipher *cc;
171   const gcmac *mc;
172   gcipher *c, *cx;
173   gmac *m;
174   octet *t; size_t tsz;
175 } gencomp_encctx;
176
177 static bulk *gencomp_init(key *k, const char *calg, const char *halg)
178 {
179   gencomp_encctx *ctx = CREATE(gencomp_encctx);
180   const char *q;
181   dstr d = DSTR_INIT, t = DSTR_INIT;
182
183   key_fulltag(k, &t);
184
185   if ((q = key_getattr(0, k, "cipher")) != 0) calg = q;
186   if (!calg) ctx->cc = &blowfish_cbc;
187   else if ((ctx->cc = gcipher_byname(calg)) == 0) {
188     die(EXIT_FAILURE, "encryption scheme `%s' not found in key `%s'",
189         calg, t.buf);
190   }
191
192   dstr_reset(&d);
193   if ((q = key_getattr(0, k, "mac")) == 0) {
194     dstr_putf(&d, "%s-hmac", halg);
195     q = d.buf;
196   }
197   if ((ctx->mc = gmac_byname(q)) == 0) {
198     die(EXIT_FAILURE,
199         "message authentication code `%s' not found in key `%s'",
200         q, t.buf);
201   }
202
203   return (&ctx->b);
204 }
205
206 static int gencomp_setup(bulk *b, gcipher *cx)
207 {
208   gencomp_encctx *ctx = (gencomp_encctx *)b;
209   size_t cn, mn, n;
210   octet *kd;
211
212   ctx->cx = cx;
213   n = ctx->cc->blksz;
214   cn = keysz(0, ctx->cc->keysz); if (cn > n) n = cn;
215   mn = keysz(0, ctx->mc->keysz); if (mn > n) n = mn;
216   ctx->t = kd = xmalloc(n); ctx->tsz = n;
217   GC_ENCRYPT(cx, 0, kd, cn);
218   ctx->c = GC_INIT(ctx->cc, kd, cn);
219   GC_ENCRYPT(cx, 0, kd, mn);
220   ctx->m = GM_KEY(ctx->mc, kd, mn);
221   return (0);
222 }
223
224 static size_t gencomp_overhead(bulk *b)
225 {
226   gencomp_encctx *ctx = (gencomp_encctx *)b;
227   return (ctx->cc->blksz + ctx->mc->hashsz); }
228
229 static void gencomp_destroy(bulk *b)
230 {
231   gencomp_encctx *ctx = (gencomp_encctx *)b;
232
233   GC_DESTROY(ctx->c);
234   GC_DESTROY(ctx->m);
235   xfree(ctx->t);
236   DESTROY(ctx);
237 }
238
239 static const char *gencomp_encdoit(bulk *b, uint32 seq, buf *bb,
240                                    const void *p, size_t sz)
241 {
242   gencomp_encctx *ctx = (gencomp_encctx *)b;
243   octet *tag, *ct;
244   ghash *h = GM_INIT(ctx->m);
245
246   GH_HASHU32(h, seq);
247   if (ctx->cc->blksz) {
248     GC_ENCRYPT(ctx->cx, 0, ctx->t, ctx->cc->blksz);
249     GC_SETIV(ctx->c, ctx->t);
250   }
251   tag = buf_get(bb, ctx->mc->hashsz); assert(tag);
252   ct = buf_get(bb, sz); assert(ct);
253   GC_ENCRYPT(ctx->c, p, ct, sz);
254   GH_HASH(h, ct, sz);
255   GH_DONE(h, tag);
256   GH_DESTROY(h);
257   return (0);
258 }
259
260 static const char *gencomp_decdoit(bulk *b, uint32 seq, buf *bb,
261                                    const void *p, size_t sz)
262 {
263   gencomp_encctx *ctx = (gencomp_encctx *)b;
264   buf bin;
265   const octet *tag, *ct;
266   octet *pt;
267   ghash *h;
268   int ok;
269
270   buf_init(&bin, (/*unconst*/ void *)p, sz);
271   if ((tag = buf_get(&bin, ctx->mc->hashsz)) == 0) return ("no tag");
272   ct = BCUR(&bin); sz = BLEFT(&bin);
273   pt = buf_get(bb, sz); assert(pt);
274
275   h = GM_INIT(ctx->m);
276   GH_HASHU32(h, seq);
277   GH_HASH(h, ct, sz);
278   ok = ct_memeq(tag, GH_DONE(h, 0), ctx->mc->hashsz);
279   GH_DESTROY(h);
280   if (!ok) return ("authentication failure");
281
282   if (ctx->cc->blksz) {
283     GC_ENCRYPT(ctx->cx, 0, ctx->t, ctx->cc->blksz);
284     GC_SETIV(ctx->c, ctx->t);
285   }
286   GC_DECRYPT(ctx->c, ct, pt, sz);
287   return (0);
288 }
289
290 static const bulkops gencomp_encops = {
291   gencomp_init, gencomp_setup, gencomp_overhead,
292   gencomp_encdoit, gencomp_destroy
293 }, gencomp_decops = {
294   gencomp_init, gencomp_setup, gencomp_overhead,
295   gencomp_decdoit, gencomp_destroy
296 };
297
298 const struct bulktab bulktab[] = {
299   { "gencomp",  &gencomp_encops,        &gencomp_decops },
300   { "naclbox",  &naclbox_encops,        &naclbox_decops },
301   { 0,          0,                      0 }
302 };
303
304 /*----- Key encapsulation -------------------------------------------------*/
305
306 /* --- RSA --- */
307
308 typedef struct rsa_encctx {
309   kem k;
310   rsa_pubctx rp;
311 } rsa_encctx;
312
313 static kem *rsa_encinit(key *k, void *kd)
314 {
315   rsa_encctx *re = CREATE(rsa_encctx);
316   rsa_pubcreate(&re->rp, kd);
317   return (&re->k);
318 }
319
320 static int rsa_encdoit(kem *k, dstr *d, ghash *h)
321 {
322   rsa_encctx *re = (rsa_encctx *)k;
323   mp *x = mprand_range(MP_NEW, re->rp.rp->n, &rand_global, 0);
324   mp *y = rsa_pubop(&re->rp, MP_NEW, x);
325   size_t n = mp_octets(re->rp.rp->n);
326   dstr_ensure(d, n);
327   mp_storeb(x, d->buf, n);
328   GH_HASH(h, d->buf, n);
329   mp_storeb(y, d->buf, n);
330   d->len += n;
331   mp_drop(x);
332   mp_drop(y);
333   return (0);
334 }
335
336 static const char *rsa_lengthcheck(mp *n)
337 {
338   if (mp_bits(n) < 1020) return ("key too short");
339   return (0);
340 }
341
342 static const char *rsa_enccheck(kem *k)
343 {
344   rsa_encctx *re = (rsa_encctx *)k;
345   const char *e;
346   if ((e = rsa_lengthcheck(re->rp.rp->n)) != 0) return (e);
347   return (0);
348 }
349
350 static void rsa_encdestroy(kem *k)
351 {
352   rsa_encctx *re = (rsa_encctx *)k;
353   rsa_pubdestroy(&re->rp);
354   DESTROY(re);
355 }
356
357 static const kemops rsa_encops = {
358   rsa_pubfetch, sizeof(rsa_pub),
359   rsa_encinit, rsa_encdoit, rsa_enccheck, rsa_encdestroy
360 };
361
362 typedef struct rsa_decctx {
363   kem k;
364   rsa_privctx rp;
365 } rsa_decctx;
366
367 static kem *rsa_decinit(key *k, void *kd)
368 {
369   rsa_decctx *rd = CREATE(rsa_decctx);
370   rsa_privcreate(&rd->rp, kd, &rand_global);
371   return (&rd->k);
372 }
373
374 static int rsa_decdoit(kem *k, dstr *d, ghash *h)
375 {
376   rsa_decctx *rd = (rsa_decctx *)k;
377   mp *x = mp_loadb(MP_NEW, d->buf, d->len);
378   size_t n;
379   char *p;
380
381   if (MP_CMP(x, >=, rd->rp.rp->n)) {
382     mp_drop(x);
383     return (-1);
384   }
385   n = mp_octets(rd->rp.rp->n);
386   p = xmalloc(n);
387   x = rsa_privop(&rd->rp, x, x);
388   mp_storeb(x, p, n);
389   GH_HASH(h, p, n);
390   mp_drop(x);
391   xfree(p);
392   return (0);
393 }
394
395 static const char *rsa_deccheck(kem *k)
396 {
397   rsa_decctx *rd = (rsa_decctx *)k;
398   const char *e;
399   if ((e = rsa_lengthcheck(rd->rp.rp->n)) != 0) return (e);
400   return (0);
401 }
402
403 static void rsa_decdestroy(kem *k)
404 {
405   rsa_decctx *rd = (rsa_decctx *)k;
406   rsa_privdestroy(&rd->rp);
407   DESTROY(rd);
408 }
409
410 static const kemops rsa_decops = {
411   rsa_privfetch, sizeof(rsa_priv),
412   rsa_decinit, rsa_decdoit, rsa_deccheck, rsa_decdestroy
413 };
414
415 /* --- DH and EC --- */
416
417 typedef struct dh_encctx {
418   kem k;
419   group *g;
420   mp *x;
421   ge *y;
422 } dh_encctx;
423
424 static dh_encctx *dh_doinit(key *k, const gprime_param *gp, mp *y,
425                             group *(*makegroup)(const gprime_param *),
426                             const char *what)
427 {
428   dh_encctx *de = CREATE(dh_encctx);
429   dstr t = DSTR_INIT;
430
431   key_fulltag(k, &t);
432   if ((de->g = makegroup(gp)) == 0)
433     die(EXIT_FAILURE, "bad %s group in key `%s'", what, t.buf);
434   de->x = MP_NEW;
435   de->y = G_CREATE(de->g);
436   if (G_FROMINT(de->g, de->y, y))
437     die(EXIT_FAILURE, "bad public key `%s'", t.buf);
438   dstr_destroy(&t);
439   return (de);
440 }
441
442 static dh_encctx *ec_doinit(key *k, const char *cstr, const ec *y)
443 {
444   dh_encctx *de = CREATE(dh_encctx);
445   ec_info ei;
446   const char *e;
447   dstr t = DSTR_INIT;
448
449   key_fulltag(k, &t);
450   if ((e = ec_getinfo(&ei, cstr)) != 0 ||
451       (de->g = group_ec(&ei)) == 0)
452     die(EXIT_FAILURE, "bad elliptic curve spec in key `%s': %s", t.buf, e);
453   de->x = MP_NEW;
454   de->y = G_CREATE(de->g);
455   if (G_FROMEC(de->g, de->y, y))
456     die(EXIT_FAILURE, "bad public curve point `%s'", t.buf);
457   dstr_destroy(&t);
458   return (de);
459 }
460
461 static kem *dh_encinit(key *k, void *kd)
462 {
463   dh_pub *dp = kd;
464   dh_encctx *de = dh_doinit(k, &dp->dp, dp->y, group_prime, "prime");
465   return (&de->k);
466 }
467
468 static kem *bindh_encinit(key *k, void *kd)
469 {
470   dh_pub *dp = kd;
471   dh_encctx *de = dh_doinit(k, &dp->dp, dp->y, group_binary, "binary");
472   return (&de->k);
473 }
474
475 static kem *ec_encinit(key *k, void *kd)
476 {
477   ec_pub *ep = kd;
478   dh_encctx *de = ec_doinit(k, ep->cstr, &ep->p);
479   return (&de->k);
480 }
481
482 static int dh_encdoit(kem *k, dstr *d, ghash *h)
483 {
484   dh_encctx *de = (dh_encctx *)k;
485   mp *r = mprand_range(MP_NEW, de->g->r, &rand_global, 0);
486   ge *x = G_CREATE(de->g);
487   ge *y = G_CREATE(de->g);
488   size_t n = de->g->noctets;
489   buf b;
490
491   G_EXP(de->g, x, de->g->g, r);
492   G_EXP(de->g, y, de->y, r);
493   dstr_ensure(d, n);
494   buf_init(&b, d->buf, n);
495   G_TORAW(de->g, &b, y);
496   GH_HASH(h, BBASE(&b), BLEN(&b));
497   buf_init(&b, d->buf, n);
498   G_TORAW(de->g, &b, x);
499   GH_HASH(h, BBASE(&b), BLEN(&b));
500   d->len += BLEN(&b);
501   mp_drop(r);
502   G_DESTROY(de->g, x);
503   G_DESTROY(de->g, y);
504   return (0);
505 }
506
507 static const char *dh_enccheck(kem *k)
508 {
509   dh_encctx *de = (dh_encctx *)k;
510   const char *e;
511   if ((e = G_CHECK(de->g, &rand_global)) != 0)
512     return (0);
513   if (group_check(de->g, de->y))
514     return ("public key not in subgroup");
515   return (0);
516 }
517
518 static void dh_encdestroy(kem *k)
519 {
520   dh_encctx *de = (dh_encctx *)k;
521   G_DESTROY(de->g, de->y);
522   mp_drop(de->x);
523   G_DESTROYGROUP(de->g);
524   DESTROY(de);
525 }
526
527 static const kemops dh_encops = {
528   dh_pubfetch, sizeof(dh_pub),
529   dh_encinit, dh_encdoit, dh_enccheck, dh_encdestroy
530 };
531
532 static const kemops bindh_encops = {
533   dh_pubfetch, sizeof(dh_pub),
534   bindh_encinit, dh_encdoit, dh_enccheck, dh_encdestroy
535 };
536
537 static const kemops ec_encops = {
538   ec_pubfetch, sizeof(ec_pub),
539   ec_encinit, dh_encdoit, dh_enccheck, dh_encdestroy
540 };
541
542 static kem *dh_decinit(key *k, void *kd)
543 {
544   dh_priv *dp = kd;
545   dh_encctx *de = dh_doinit(k, &dp->dp, dp->y, group_prime, "prime");
546   de->x = MP_COPY(dp->x);
547   return (&de->k);
548 }
549
550 static kem *bindh_decinit(key *k, void *kd)
551 {
552   dh_priv *dp = kd;
553   dh_encctx *de = dh_doinit(k, &dp->dp, dp->y, group_binary, "binary");
554   de->x = MP_COPY(dp->x);
555   return (&de->k);
556 }
557
558 static kem *ec_decinit(key *k, void *kd)
559 {
560   ec_priv *ep = kd;
561   dh_encctx *de = ec_doinit(k, ep->cstr, &ep->p);
562   de->x = MP_COPY(ep->x);
563   return (&de->k);
564 }
565
566 static int dh_decdoit(kem *k, dstr *d, ghash *h)
567 {
568   dh_encctx *de = (dh_encctx *)k;
569   ge *x = G_CREATE(de->g);
570   size_t n = de->g->noctets;
571   void *p = xmalloc(n);
572   buf b;
573   int rc = -1;
574
575   buf_init(&b, d->buf, d->len);
576   if (G_FROMRAW(de->g, &b, x) || group_check(de->g, x))
577     goto done;
578   G_EXP(de->g, x, x, de->x);
579   buf_init(&b, p, n);
580   G_TORAW(de->g, &b, x);
581   GH_HASH(h, BBASE(&b), BLEN(&b));
582   GH_HASH(h, d->buf, d->len);
583   rc = 0;
584 done:
585   G_DESTROY(de->g, x);
586   xfree(p);
587   return (rc);
588 }
589
590 static const kemops dh_decops = {
591   dh_privfetch, sizeof(dh_priv),
592   dh_decinit, dh_decdoit, dh_enccheck, dh_encdestroy
593 };
594
595 static const kemops bindh_decops = {
596   dh_privfetch, sizeof(dh_priv),
597   bindh_decinit, dh_decdoit, dh_enccheck, dh_encdestroy
598 };
599
600 static const kemops ec_decops = {
601   ec_privfetch, sizeof(ec_priv),
602   ec_decinit, dh_decdoit, dh_enccheck, dh_encdestroy
603 };
604
605 /* --- Symmetric --- */
606
607 typedef struct symm_ctx {
608   kem k;
609   key_packdef kp;
610   key_bin kb;
611 } symm_ctx;
612
613 static kem *symm_init(key *k, void *kd)
614 {
615   symm_ctx *s;
616   dstr d = DSTR_INIT;
617   int err;
618
619   s = CREATE(symm_ctx);
620
621   key_fulltag(k, &d);
622   s->kp.e = KENC_BINARY;
623   s->kp.p = &s->kb;
624   s->kp.kd = 0;
625
626   if ((err = key_unpack(&s->kp, kd, &d)) != 0) {
627     die(EXIT_FAILURE, "failed to unpack symmetric key `%s': %s",
628         d.buf, key_strerror(err));
629   }
630   dstr_destroy(&d);
631   return (&s->k);
632 }
633
634 static int symm_decdoit(kem *k, dstr *d, ghash *h)
635 {
636   symm_ctx *s = (symm_ctx *)k;
637
638   GH_HASH(h, s->kb.k, s->kb.sz);
639   GH_HASH(h, d->buf, d->len);
640   return (0);
641 }
642
643 static int symm_encdoit(kem *k, dstr *d, ghash *h)
644 {
645   dstr_ensure(d, h->ops->c->hashsz);
646   d->len += h->ops->c->hashsz;
647   rand_get(RAND_GLOBAL, d->buf, d->len);
648   return (symm_decdoit(k, d, h));
649 }
650
651 static const char *symm_check(kem *k) { return (0); }
652
653 static void symm_destroy(kem *k)
654   { symm_ctx *s = (symm_ctx *)k; key_unpackdone(&s->kp); }
655
656 static const kemops symm_encops = {
657   0, 0,
658   symm_init, symm_encdoit, symm_check, symm_destroy
659 };
660
661 static const kemops symm_decops = {
662   0, 0,
663   symm_init, symm_decdoit, symm_check, symm_destroy
664 };
665
666 /* --- The switch table --- */
667
668 const struct kemtab kemtab[] = {
669   { "rsa",      &rsa_encops,    &rsa_decops },
670   { "dh",       &dh_encops,     &dh_decops },
671   { "bindh",    &bindh_encops,  &bindh_decops },
672   { "ec",       &ec_encops,     &ec_decops },
673   { "symm",     &symm_encops,   &symm_decops },
674   { 0,          0,              0 }
675 };
676
677 /* --- @getkem@ --- *
678  *
679  * Arguments:   @key *k@ = the key to load
680  *              @const char *app@ = application name
681  *              @int wantpriv@ = nonzero if we want to decrypt
682  *              @bulk **bc@ = bulk crypto context to set up
683  *
684  * Returns:     A key-encapsulating thing.
685  *
686  * Use:         Loads a key.
687  */
688
689 kem *getkem(key *k, const char *app, int wantpriv, bulk **bc)
690 {
691   const char *kalg, *halg = 0, *balg = 0;
692   dstr d = DSTR_INIT;
693   dstr t = DSTR_INIT;
694   size_t n;
695   char *p = 0;
696   const char *q;
697   kem *kk;
698   const struct kemtab *kt;
699   const kemops *ko;
700   const struct bulktab *bt;
701   const bulkops *bo;
702   void *kd;
703   int e;
704   key_packdef *kp;
705
706   /* --- Setup stuff --- */
707
708   key_fulltag(k, &t);
709
710   /* --- Get the KEM name --- *
711    *
712    * Take the attribute if it's there; otherwise use the key type.
713    */
714
715   n = strlen(app);
716   if ((q = key_getattr(0, k, "kem")) != 0) {
717     dstr_puts(&d, q);
718     p = d.buf;
719   } else if (strncmp(k->type, app, n) == 0 && k->type[n] == '-') {
720     dstr_puts(&d, k->type);
721     p = d.buf + n + 1;
722   } else
723     die(EXIT_FAILURE, "no KEM for key `%s'", t.buf);
724   kalg = p;
725
726   /* --- Grab the bulk encryption scheme --- *
727    *
728    * Grab it from the KEM if it's there, but override it from the attribute.
729    */
730
731   if (p && (p = strchr(p, '/')) != 0) {
732     *p++ = 0;
733     balg = p;
734   }
735   if ((q = key_getattr(0, k, "bulk")) != 0)
736     balg = q;
737
738   /* --- Grab the hash function --- */
739
740   if (p && (p = strchr(p, '/')) != 0) {
741     *p++ = 0;
742     halg = p;
743   }
744   if ((q = key_getattr(0, k, "hash")) != 0)
745     halg = q;
746
747   /* --- Instantiate the KEM --- */
748
749   for (kt = kemtab; kt->name; kt++) {
750     if (strcmp(kt->name, kalg) == 0)
751       goto k_found;
752   }
753   die(EXIT_FAILURE, "key encapsulation mechanism `%s' not found in key `%s'",
754       kalg, t.buf);
755 k_found:;
756   ko = wantpriv ? kt->decops : kt->encops;
757   if (!ko->kf) {
758     kd = k->k;
759     key_incref(kd);
760     kp = 0;
761   } else {
762     kd = xmalloc(ko->kdsz);
763     kp = key_fetchinit(ko->kf, 0, kd);
764     if ((e = key_fetch(kp, k)) != 0) {
765       die(EXIT_FAILURE, "error fetching key `%s': %s",
766           t.buf, key_strerror(e));
767     }
768   }
769   kk = ko->init(k, kd);
770   kk->kp = kp;
771   kk->ops = ko;
772   kk->kd = kd;
773
774   /* --- Set up the bulk crypto --- */
775
776   if (!halg)
777     kk->hc = &rmd160;
778   else if ((kk->hc = ghash_byname(halg)) == 0) {
779     die(EXIT_FAILURE, "hash algorithm `%s' not found in key `%s'",
780         halg, t.buf);
781   }
782
783   dstr_reset(&d);
784   if ((q = key_getattr(0, k, "kdf")) == 0) {
785     dstr_putf(&d, "%s-mgf", kk->hc->name);
786     q = d.buf;
787   }
788   if ((kk->cxc = gcipher_byname(q)) == 0) {
789     die(EXIT_FAILURE, "encryption scheme (KDF) `%s' not found in key `%s'",
790         q, t.buf);
791   }
792
793   if (!balg)
794     bt = bulktab;
795   else {
796     for (bt = bulktab, bo = 0; bt->name; bt++) {
797       if (strcmp(balg, bt->name) == 0)
798         { balg = 0; goto b_found; }
799       n = strlen(bt->name);
800       if (strncmp(balg, bt->name, n) == 0 && balg[n] == '-')
801         { balg += n + 1; goto b_found; }
802     }
803     bt = bulktab;
804   b_found:;
805   }
806   bo = wantpriv ? bt->decops : bt->encops;
807   *bc = bo->init(k, balg, kk->hc->name);
808   (*bc)->ops = bo;
809
810   /* --- Tidy up --- */
811
812   dstr_destroy(&d);
813   dstr_destroy(&t);
814   return (kk);
815 }
816
817 /* --- @setupkem@ --- *
818  *
819  * Arguments:   @kem *k@ = key-encapsulation thing
820  *              @dstr *d@ = key-encapsulation data
821  *              @bulk *bc@ = bulk crypto context to set up
822  *
823  * Returns:     Zero on success, nonzero on failure.
824  *
825  * Use:         Initializes all the various symmetric things from a KEM.
826  */
827
828 int setupkem(kem *k, dstr *d, bulk *bc)
829 {
830   octet *kd;
831   size_t n;
832   ghash *h;
833   int rc = -1;
834
835   h = GH_INIT(k->hc);
836   if (k->ops->doit(k, d, h))
837     goto done;
838   n = keysz(GH_CLASS(h)->hashsz, k->cxc->keysz);
839   if (!n)
840     goto done;
841   kd = GH_DONE(h, 0);
842   k->cx = GC_INIT(k->cxc, kd, n);
843   bc->ops->setup(bc, k->cx);
844
845   rc = 0;
846 done:
847   GH_DESTROY(h);
848   return (rc);
849 }
850
851 /* --- @freekem@ --- *
852  *
853  * Arguments:   @kem *k@ = key-encapsulation thing
854  *
855  * Returns:     ---
856  *
857  * Use:         Frees up a key-encapsulation thing.
858  */
859
860 void freekem(kem *k)
861 {
862   if (!k->ops->kf)
863     key_drop(k->kd);
864   else {
865     key_fetchdone(k->kp);
866     xfree(k->kd);
867   }
868   GC_DESTROY(k->cx);
869   k->ops->destroy(k);
870 }
871
872 /*----- That's all, folks -------------------------------------------------*/