]> git.tuebingen.mpg.de Git - paraslash.git/blob - gcrypt.c
openssl: Move get_private_key() down.
[paraslash.git] / gcrypt.c
1 /* Copyright (C) 2011 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file gcrypt.c Libgrcypt-based encryption/decryption routines. */
4
5 #include <regex.h>
6 #include <gcrypt.h>
7
8 #include "para.h"
9 #include "error.h"
10 #include "string.h"
11 #include "crypt.h"
12 #include "crypt_backend.h"
13 #include "fd.h"
14 #include "base64.h"
15 #include "portable_io.h"
16
17 //#define GCRYPT_DEBUG 1
18
19 #ifdef GCRYPT_DEBUG
20 static void dump_buffer(const char *msg, unsigned char *buf, int len)
21 {
22         int i;
23
24         fprintf(stderr, "%s (%d bytes): ", msg, len);
25         for (i = 0; i < len; i++)
26                 fprintf(stderr, "%02x ", buf[i]);
27         fprintf(stderr, "\n");
28 }
29 #else
30 /** Empty. Define GCRYPT_DEBUG to dump buffers. */
31 #define dump_buffer(a, b, c)
32 #endif
33
34 void hash_function(const char *data, unsigned long len, unsigned char *hash)
35 {
36         gcry_error_t gret;
37         gcry_md_hd_t handle;
38         unsigned char *md;
39
40         gret = gcry_md_open(&handle, GCRY_MD_SHA1, 0);
41         assert(gret == 0);
42         gcry_md_write(handle, data, (size_t)len);
43         gcry_md_final(handle);
44         md = gcry_md_read(handle, GCRY_MD_SHA1);
45         assert(md);
46         memcpy(hash, md, HASH_SIZE);
47         gcry_md_close(handle);
48 }
49
50 void get_random_bytes_or_die(unsigned char *buf, int num)
51 {
52         gcry_randomize(buf, (size_t)num, GCRY_STRONG_RANDOM);
53 }
54
55 /*
56  * This is called at the beginning of every program that uses libgcrypt. The
57  * call to gcry_check_version() initializes the gcrypt library and checks that
58  * we have at least the minimal required version.
59  */
60 void crypt_init(void)
61 {
62         const char *req_ver = "1.5.0";
63         int seed;
64
65         if (!gcry_check_version(req_ver)) {
66                 PARA_EMERG_LOG("fatal: need at least libgcrypt-%s, have: %s\n",
67                         req_ver, gcry_check_version(NULL));
68                 exit(EXIT_FAILURE);
69         }
70
71         /*
72          * Allocate a pool of secure memory. This also drops privileges where
73          * needed.
74          */
75         gcry_control(GCRYCTL_INIT_SECMEM, 65536, 0);
76
77         /* Tell Libgcrypt that initialization has completed. */
78         gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
79
80         get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
81         srandom(seed);
82 }
83
84 void crypt_shutdown(void)
85 {
86         /*
87          * WK does not see a way to apply a patch for the sake of Valgrind, so
88          * as of 2018 libgrypt has no deinitialization routine to free the
89          * resources on exit.
90          */
91 }
92
93 /** S-expression for the public part of an RSA key. */
94 #define RSA_PUBKEY_SEXP "(public-key (rsa (n %m) (e %m)))"
95 /** S-expression for a private RSA key. */
96 #define RSA_PRIVKEY_SEXP "(private-key (rsa (n %m) (e %m) (d %m) (p %m) (q %m) (u %m)))"
97 /** S-expression for decryption. */
98 #define RSA_DECRYPT_SEXP "(enc-val(flags oaep)(rsa(a %m)))"
99
100 struct asymmetric_key {
101         gcry_sexp_t sexp;
102         int num_bytes;
103 };
104
105 static const char *gcrypt_strerror(gcry_error_t gret)
106 {
107         return gcry_strerror(gcry_err_code(gret));
108 }
109
110 /** Private PEM keys (legacy format) start with this header. */
111 #define PRIVATE_PEM_KEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
112 /** Private OPENSSH keys (RFC4716) start with this header. */
113 #define PRIVATE_OPENSSH_KEY_HEADER "-----BEGIN OPENSSH PRIVATE KEY-----"
114 /** Private PEM keys (legacy format) end with this footer. */
115 #define PRIVATE_PEM_KEY_FOOTER "-----END RSA PRIVATE KEY-----"
116 /** Private OPENSSH keys (RFC4716) end with this footer. */
117 #define PRIVATE_OPENSSH_KEY_FOOTER "-----END OPENSSH PRIVATE KEY-----"
118 /** Legacy PEM keys (openssh-7.7 and earlier, paraslash.0.6.2 and earlier) */
119 #define PKT_PEM (0)
120 /** OPENSSH keys (since openssh-7.8, paraslash.0.6.3) */
121 #define PKT_OPENSSH (1)
122
123 static int decode_private_key(const char *key_file, unsigned char **result,
124                 size_t *blob_size)
125 {
126         int ret, ret2, i, j, key_type;
127         void *map;
128         size_t map_size, key_size;
129         unsigned char *blob = NULL;
130         char *begin, *footer, *key;
131
132         ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
133         if (ret < 0)
134                 goto out;
135         ret = -E_KEY_MARKER;
136         if (strncmp(map, PRIVATE_PEM_KEY_HEADER,
137                         strlen(PRIVATE_PEM_KEY_HEADER)) == 0) {
138                 key_type = PKT_PEM;
139                 begin = map + strlen(PRIVATE_PEM_KEY_HEADER);
140                 footer = strstr(map, PRIVATE_PEM_KEY_FOOTER);
141                 PARA_INFO_LOG("detected legacy PEM key %s\n", key_file);
142         } else if (strncmp(map, PRIVATE_OPENSSH_KEY_HEADER,
143                         strlen(PRIVATE_OPENSSH_KEY_HEADER)) == 0) {
144                 key_type = PKT_OPENSSH;
145                 begin = map + strlen(PRIVATE_OPENSSH_KEY_HEADER);
146                 footer = strstr(map, PRIVATE_OPENSSH_KEY_FOOTER);
147                 PARA_INFO_LOG("detected openssh key %s\n", key_file);
148         } else
149                 goto unmap;
150         if (!footer)
151                 goto unmap;
152         /* skip whitespace at the beginning */
153         for (; begin < footer; begin++) {
154                 if (para_isspace(*begin))
155                         continue;
156                 break;
157         }
158         ret = -E_KEY_MARKER;
159         if (begin >= footer)
160                 goto unmap;
161
162         key_size = footer - begin;
163         key = para_malloc(key_size + 1);
164         for (i = 0, j = 0; begin + i < footer; i++) {
165                 if (para_isspace(begin[i]))
166                         continue;
167                 key[j++] = begin[i];
168         }
169         key[j] = '\0';
170         ret = base64_decode(key, j, (char **)&blob, blob_size);
171         free(key);
172         if (ret < 0)
173                 goto unmap;
174         ret = key_type;
175 unmap:
176         ret2 = para_munmap(map, map_size);
177         if (ret >= 0 && ret2 < 0)
178                 ret = ret2;
179         if (ret < 0) {
180                 free(blob);
181                 blob = NULL;
182         }
183 out:
184         *result = blob;
185         return ret;
186 }
187
188 /** ASN Types and their code. */
189 enum asn1_types {
190         /** The next object is an integer. */
191         ASN1_TYPE_INTEGER = 0x2,
192         /** Bit string object. */
193         ASN1_TYPE_BIT_STRING = 0x03,
194         /** Keys start with one big type sequence. */
195         ASN1_TYPE_SEQUENCE = 0x30,
196 };
197
198 /* bit 6 has value 0 */
199 static inline bool is_primitive(unsigned char c)
200 {
201         return (c & (1<<6)) == 0;
202 }
203
204 static inline bool is_primitive_integer(unsigned char c)
205 {
206         if (!is_primitive(c))
207                 return false;
208         return (c & 0x1f) == ASN1_TYPE_INTEGER;
209 }
210
211 /* Bit 8 is zero (and bits 7-1 give the length) */
212 static inline bool is_short_form(unsigned char c)
213 {
214         return (c & 0x80) == 0;
215 }
216
217 static inline int get_short_form_length(unsigned char c)
218 {
219         return c & 0x7f;
220 }
221
222 static inline int get_long_form_num_length_bytes(unsigned char c)
223 {
224         return c & 0x7f;
225 }
226
227 /*
228  * Returns: Number of bytes scanned. This may differ from the value returned via
229  * bitsp because the latter does not include the ASN.1 prefix and a leading
230  * zero is not considered as an additional byte for the number of bits.
231  */
232 static int read_pem_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
233                 unsigned *bitsp)
234 {
235         int i, bn_size;
236         gcry_error_t gret;
237         unsigned char *cp = start;
238
239         if (!is_primitive_integer(*cp))
240                 return -E_BAD_PRIVATE_KEY;
241         cp++;
242         if (is_short_form(*cp)) {
243                 bn_size = get_short_form_length(*cp);
244                 cp++;
245         } else {
246                 int num_bytes = get_long_form_num_length_bytes(*cp);
247                 if (cp + num_bytes > end)
248                         return -E_BAD_PRIVATE_KEY;
249                 if (num_bytes > 4) /* nobody has such a large modulus */
250                         return -E_BAD_PRIVATE_KEY;
251                 cp++;
252                 bn_size = 0;
253                 for (i = 0; i < num_bytes; i++, cp++)
254                         bn_size = (bn_size << 8) + *cp;
255         }
256         PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
257         gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
258         if (gret) {
259                 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
260                         gcry_strerror(gcry_err_code(gret)));
261                 return-E_MPI_SCAN;
262         }
263         /*
264          * Don't take the first leading zero into account for the size of the
265          * bignum.
266          */
267         if (*cp == '\0') {
268                 cp++;
269                 bn_size--;
270         }
271         if (bitsp)
272                 *bitsp = bn_size * 8;
273         cp += bn_size;
274 //      unsigned char *buf;
275 //      gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
276 //      PARA_CRIT_LOG("bn: %s\n", buf);
277         return cp - start;
278 }
279
280 struct rsa_params {
281         gcry_mpi_t n, e, d, p, q, u;
282 };
283
284 static int read_pem_rsa_params(unsigned char *start, unsigned char *end,
285                 struct rsa_params *p)
286 {
287         unsigned char *cp = start;
288         unsigned bits;
289         int ret;
290
291         ret = read_pem_bignum(cp, end, &p->n, &bits);
292         if (ret < 0)
293                 return ret;
294         cp += ret;
295         ret = read_pem_bignum(cp, end, &p->e, NULL);
296         if (ret < 0)
297                 goto release_n;
298         cp += ret;
299         ret = read_pem_bignum(cp, end, &p->d, NULL);
300         if (ret < 0)
301                 goto release_e;
302         cp += ret;
303         ret = read_pem_bignum(cp, end, &p->p, NULL);
304         if (ret < 0)
305                 goto release_d;
306         cp += ret;
307         ret = read_pem_bignum(cp, end, &p->q, NULL);
308         if (ret < 0)
309                 goto release_p;
310         cp += ret;
311         ret = read_pem_bignum(cp, end, &p->u, NULL);
312         if (ret < 0)
313                 goto release_q;
314         return bits;
315 release_q:
316         gcry_mpi_release(p->q);
317 release_p:
318         gcry_mpi_release(p->p);
319 release_d:
320         gcry_mpi_release(p->d);
321 release_e:
322         gcry_mpi_release(p->e);
323 release_n:
324         gcry_mpi_release(p->n);
325         return ret;
326 }
327
328 static int find_pem_bignum_offset(const unsigned char *data, int len)
329 {
330         const unsigned char *p = data, *end = data + len;
331
332         /* like the public key, the whole thing is contained in a sequence */
333         if (*p != ASN1_TYPE_SEQUENCE)
334                 return -E_ASN1_PARSE;
335         p++;
336         if (p >= end)
337                 return -E_ASN1_PARSE;
338         if (is_short_form(*p))
339                 p++;
340         else
341                 p += 1 + get_long_form_num_length_bytes(*p);
342         if (p >= end)
343                 return -E_ASN1_PARSE;
344
345         /* skip next integer */
346         if (*p != ASN1_TYPE_INTEGER)
347                 return -E_ASN1_PARSE;
348         p++;
349         if (p >= end)
350                 return -E_ASN1_PARSE;
351         if (is_short_form(*p))
352                 p += 1 + get_short_form_length(*p);
353         else
354                 p += 1 + get_long_form_num_length_bytes(*p);
355         if (p >= end)
356                 return -E_ASN1_PARSE;
357         return p - data;
358 }
359
360 static int read_openssh_bignum(unsigned char *start, unsigned char *end,
361                 gcry_mpi_t *bn, unsigned *bitsp)
362 {
363         gcry_error_t gret;
364         size_t nscanned;
365         unsigned bits;
366
367         gret = gcry_mpi_scan(bn, GCRYMPI_FMT_SSH, start, end - start, &nscanned);
368         if (gret) {
369                 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
370                         gcry_strerror(gcry_err_code(gret)));
371                 return -E_MPI_SCAN;
372         }
373         bits = (nscanned - 4 - (start[4] == '\0')) * 8;
374         if (bitsp)
375                 *bitsp = bits;
376         PARA_DEBUG_LOG("scanned %u-bit bignum\n", bits);
377         return nscanned;
378 }
379
380 static int read_openssh_rsa_params(unsigned char *start, unsigned char *end,
381                 struct rsa_params *p)
382 {
383         unsigned char *cp = start;
384         unsigned bits;
385         int ret;
386
387         ret = read_openssh_bignum(cp, end, &p->n, &bits);
388         if (ret < 0)
389                 return ret;
390         cp += ret;
391         ret = read_openssh_bignum(cp, end, &p->e, NULL);
392         if (ret < 0)
393                 goto release_n;
394         cp += ret;
395         ret = read_openssh_bignum(cp, end, &p->d, NULL);
396         if (ret < 0)
397                 goto release_e;
398         cp += ret;
399         ret = read_openssh_bignum(cp, end, &p->u, NULL);
400         if (ret < 0)
401                 goto release_d;
402         cp += ret;
403         ret = read_openssh_bignum(cp, end, &p->p, NULL);
404         if (ret < 0)
405                 goto release_u;
406         cp += ret;
407         ret = read_openssh_bignum(cp, end, &p->q, NULL);
408         if (ret < 0)
409                 goto release_p;
410         return bits;
411 release_p:
412         gcry_mpi_release(p->p);
413 release_u:
414         gcry_mpi_release(p->u);
415 release_d:
416         gcry_mpi_release(p->d);
417 release_e:
418         gcry_mpi_release(p->e);
419 release_n:
420         gcry_mpi_release(p->n);
421         return ret;
422 }
423
424 static int get_private_key(const char *key_file, struct asymmetric_key **result)
425 {
426         struct rsa_params params;
427         unsigned char *blob, *end;
428         unsigned bits;
429         int ret, key_type;
430         gcry_error_t gret;
431         size_t erroff, blob_size;
432         gcry_sexp_t sexp;
433         struct asymmetric_key *key;
434
435         *result = NULL;
436         ret = decode_private_key(key_file, &blob, &blob_size);
437         if (ret < 0)
438                 return ret;
439         key_type = ret;
440         end = blob + blob_size;
441         if (key_type == PKT_PEM)
442                 ret = find_pem_bignum_offset(blob, blob_size);
443         else
444                 ret = find_openssh_bignum_offset(blob, blob_size);
445         if (ret < 0)
446                 goto free_blob;
447         PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
448         if (key_type == PKT_PEM)
449                 ret = read_pem_rsa_params(blob + ret, end, &params);
450         else
451                 ret = read_openssh_rsa_params(blob + ret, end, &params);
452         if (ret < 0)
453                 goto free_blob;
454         bits = ret;
455         /*
456          * OpenSSL uses slightly different parameters than gcrypt. To use these
457          * parameters we need to swap the values of p and q and recompute u.
458          */
459         if (gcry_mpi_cmp(params.p, params.q) > 0) {
460                 gcry_mpi_swap(params.p, params.q);
461                 gcry_mpi_invm(params.u, params.p, params.q);
462         }
463         gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP, params.n,
464                 params.e, params.d, params.p, params.q, params.u);
465
466         if (gret) {
467                 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
468                         gcry_strerror(gcry_err_code(gret)));
469                 ret = -E_SEXP_BUILD;
470                 goto free_params;
471         }
472         key = para_malloc(sizeof(*key));
473         key->sexp = sexp;
474         *result = key;
475         ret = bits;
476         PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
477 free_params:
478         gcry_mpi_release(params.n);
479         gcry_mpi_release(params.e);
480         gcry_mpi_release(params.d);
481         gcry_mpi_release(params.u);
482         gcry_mpi_release(params.p);
483         gcry_mpi_release(params.q);
484
485 free_blob:
486         free(blob);
487         return ret;
488 }
489
490 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
491 {
492         unsigned char *blob, *p, *end;
493         int ret;
494         gcry_error_t gret;
495         size_t erroff, decoded_size;
496         gcry_mpi_t e, n;
497         gcry_sexp_t sexp;
498         struct asymmetric_key *key;
499         unsigned bits;
500
501         ret = decode_public_key(key_file, &blob, &decoded_size);
502         if (ret < 0)
503                 return ret;
504         p = blob + ret;
505         end = blob + decoded_size;
506         PARA_DEBUG_LOG("scanning modulus and public exponent\n");
507         ret = read_openssh_bignum(p, end, &e, NULL);
508         if (ret < 0)
509                 goto free_blob;
510         p += ret;
511         ret = read_openssh_bignum(p, end, &n, &bits);
512         if (ret < 0)
513                 goto release_e;
514         gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
515         if (gret) {
516                 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
517                         gcry_strerror(gcry_err_code(gret)));
518                 ret = -E_SEXP_BUILD;
519                 goto release_n;
520         }
521         PARA_INFO_LOG("successfully read %u bit ssh public key\n", bits);
522         key = para_malloc(sizeof(*key));
523         key->num_bytes = ret;
524         key->sexp = sexp;
525         *result = key;
526         ret = bits;
527 release_n:
528         gcry_mpi_release(n);
529 release_e:
530         gcry_mpi_release(e);
531 free_blob:
532         free(blob);
533         return ret;
534 }
535
536 void apc_free_pubkey(struct asymmetric_key *key)
537 {
538         if (!key)
539                 return;
540         gcry_sexp_release(key->sexp);
541         free(key);
542 }
543
544 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
545 {
546         const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
547
548         if (!p)
549                 return -E_RSA_DECODE;
550         memcpy(outbuf, p, *nbytes);
551         return 1;
552 }
553
554 int apc_priv_decrypt(const char *key_file, unsigned char *outbuf,
555                 unsigned char *inbuf, int inlen)
556 {
557         gcry_error_t gret;
558         int ret;
559         struct asymmetric_key *priv;
560         gcry_mpi_t in_mpi = NULL;
561         gcry_sexp_t in, out, priv_key;
562         size_t nbytes;
563
564         ret = check_private_key_file(key_file);
565         if (ret < 0)
566                 return ret;
567         PARA_INFO_LOG("decrypting %d byte input\n", inlen);
568         /* key_file -> asymmetric key priv */
569         ret = get_private_key(key_file, &priv);
570         if (ret < 0)
571                 return ret;
572
573         /* asymmetric key priv -> sexp priv_key */
574         ret = -E_SEXP_FIND;
575         priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
576         if (!priv_key)
577                 goto free_key;
578
579         /* inbuf -> in_mpi */
580         gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
581                 inlen, NULL);
582         if (gret) {
583                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
584                 ret = -E_MPI_SCAN;
585                 goto key_release;
586         }
587         /* in_mpi -> in sexp */
588         gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
589         if (gret) {
590                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
591                 ret = -E_SEXP_BUILD;
592                 goto in_mpi_release;
593         }
594
595         /* rsa decryption: in sexp -> out sexp */
596         gret = gcry_pk_decrypt(&out, in, priv_key);
597         if (gret) {
598                 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
599                 ret = -E_SEXP_DECRYPT;
600                 goto in_release;
601         }
602         ret = decode_rsa(out, outbuf, &nbytes);
603         if (ret < 0)
604                 goto out_release;
605         PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
606         ret = nbytes;
607 out_release:
608         gcry_sexp_release(out);
609 in_release:
610         gcry_sexp_release(in);
611 in_mpi_release:
612         gcry_mpi_release(in_mpi);
613 key_release:
614         gcry_sexp_release(priv_key);
615 free_key:
616         gcry_sexp_release(priv->sexp);
617         free(priv);
618         return ret;
619 }
620
621 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
622                 unsigned len, unsigned char *outbuf)
623 {
624         gcry_error_t gret;
625         gcry_sexp_t pub_key, in, out, out_a;
626         gcry_mpi_t out_mpi = NULL;
627         size_t nbytes;
628         int ret;
629
630         PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
631
632         /* get pub key */
633         pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
634         if (!pub_key)
635                 return -E_SEXP_FIND;
636         gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
637         if (gret) {
638                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
639                 ret = -E_SEXP_BUILD;
640                 goto key_release;
641         }
642         /* rsa sexp encryption: in -> out */
643         gret = gcry_pk_encrypt(&out, in, pub_key);
644         if (gret) {
645                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
646                 ret = -E_SEXP_ENCRYPT;
647                 goto in_release;
648         }
649         /* extract a, an MPI with the result of the RSA operation */
650         ret = -E_SEXP_FIND;
651         out_a = gcry_sexp_find_token(out, "a", 0);
652         if (!out_a)
653                 goto out_release;
654         /* convert sexp out_a -> out_mpi */
655         out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
656         if (!out_mpi) {
657                 ret = -E_SEXP_FIND;
658                 goto out_a_release;
659         }
660         gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
661         if (gret) {
662                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
663                 ret = -E_SEXP_ENCRYPT;
664                 goto out_mpi_release;
665         }
666         PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
667         dump_buffer("enc buf", outbuf, nbytes);
668         ret = nbytes;
669
670 out_mpi_release:
671         gcry_mpi_release(out_mpi);
672 out_a_release:
673         gcry_sexp_release(out_a);
674 out_release:
675         gcry_sexp_release(out);
676 in_release:
677         gcry_sexp_release(in);
678 key_release:
679         gcry_sexp_release(pub_key);
680         return ret;
681 }
682
683 struct stream_cipher {
684         gcry_cipher_hd_t handle;
685 };
686
687 struct stream_cipher *sc_new(const unsigned char *data, int len)
688 {
689         gcry_error_t gret;
690         struct stream_cipher *sc = para_malloc(sizeof(*sc));
691
692         assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
693         gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
694                 GCRY_CIPHER_MODE_CTR, 0);
695         assert(gret == 0);
696         gret = gcry_cipher_setkey(sc->handle, data,
697                 AES_CRT128_BLOCK_SIZE);
698         assert(gret == 0);
699         gret = gcry_cipher_setctr(sc->handle,
700                 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
701         assert(gret == 0);
702         return sc;
703 }
704
705 void sc_free(struct stream_cipher *sc)
706 {
707         if (!sc)
708                 return;
709         gcry_cipher_close(sc->handle);
710         free(sc);
711 }
712
713 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
714 {
715         gcry_cipher_hd_t handle = sc->handle;
716         gcry_error_t gret;
717
718         /* perform in-place encryption */
719         *dst = *src;
720         gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,
721                 NULL, 0);
722         assert(gret == 0);
723 }