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