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