d4b87d3c9bbac8e7afe3a1835b81fe8b0bd34c11
[oweals/gnunet.git] / src / util / crypto_rsa.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/crypto_rsa.c
23  * @brief public key cryptography (RSA) with libgcrypt
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include <gcrypt.h>
28 #include "gnunet_common.h"
29 #include "gnunet_util_lib.h"
30
31 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
32
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
34
35 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
36
37 #define HOSTKEY_LEN 2048
38
39 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
40
41
42 /**
43  * The private information of an RSA key pair.
44  * NOTE: this must match the definition in crypto_ksk.c and gnunet-rsa.c!
45  */
46 struct GNUNET_CRYPTO_RsaPrivateKey
47 {
48   /**
49    * Libgcrypt S-expression for the ECC key.
50    */
51   gcry_sexp_t sexp;
52 };
53
54 /**
55  * Log an error message at log-level 'level' that indicates
56  * a failure of the command 'cmd' with the message given
57  * by gcry_strerror(rc).
58  */
59 #define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0);
60
61 /**
62  * If target != size, move target bytes to the
63  * end of the size-sized buffer and zero out the
64  * first target-size bytes.
65  *
66  * @param buf original buffer
67  * @param size number of bytes in the buffer
68  * @param target target size of the buffer
69  */
70 static void
71 adjust (unsigned char *buf, size_t size, size_t target)
72 {
73   if (size < target)
74   {
75     memmove (&buf[target - size], buf, size);
76     memset (buf, 0, target - size);
77   }
78 }
79
80
81 /**
82  * Free memory occupied by hostkey
83  * @param hostkey pointer to the memory to free
84  */
85 void
86 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
87 {
88   gcry_sexp_release (hostkey->sexp);
89   GNUNET_free (hostkey);
90 }
91
92
93 /**
94  * Extract values from an S-expression.
95  *
96  * @param array where to store the result(s)
97  * @param sexp S-expression to parse
98  * @param topname top-level name in the S-expression that is of interest
99  * @param elems names of the elements to extract
100  * @return 0 on success
101  */
102 static int
103 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
104                const char *elems)
105 {
106   gcry_sexp_t list;
107   gcry_sexp_t l2;
108   const char *s;
109   unsigned int i;
110   unsigned int idx;
111
112   list = gcry_sexp_find_token (sexp, topname, 0);
113   if (! list)  
114     return 1;  
115   l2 = gcry_sexp_cadr (list);
116   gcry_sexp_release (list);
117   list = l2;
118   if (! list)  
119     return 2;
120   idx = 0;
121   for (s = elems; *s; s++, idx++)
122   {
123     l2 = gcry_sexp_find_token (list, s, 1);
124     if (! l2)
125     {
126       for (i = 0; i < idx; i++)
127       {
128         gcry_free (array[i]);
129         array[i] = NULL;
130       }
131       gcry_sexp_release (list);
132       return 3;                 /* required parameter not found */
133     }
134     array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
135     gcry_sexp_release (l2);
136     if (! array[idx])
137     {
138       for (i = 0; i < idx; i++)
139       {
140         gcry_free (array[i]);
141         array[i] = NULL;
142       }
143       gcry_sexp_release (list);
144       return 4;                 /* required parameter is invalid */
145     }
146   }
147   gcry_sexp_release (list);
148   return 0;
149 }
150
151
152 /**
153  * Extract the public key of the host.
154  * @param priv the private key
155  * @param pub where to write the public key
156  */
157 void
158 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
159                                   *priv,
160                                   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
161                                   *pub)
162 {
163   gcry_mpi_t skey[2];
164   size_t size;
165   int rc;
166
167   rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
168   if (rc)
169     rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
170   if (rc)
171     rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
172   GNUNET_assert (0 == rc);
173   pub->len =
174       htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
175              sizeof (pub->padding));
176   pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
177   pub->padding = 0;
178   size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
179   GNUNET_assert (0 ==
180                  gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
181                                  skey[0]));
182   adjust (&pub->key[0], size, GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
183   size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
184   GNUNET_assert (0 ==
185                  gcry_mpi_print (GCRYMPI_FMT_USG,
186                                  &pub->key
187                                  [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
188                                  &size, skey[1]));
189   adjust (&pub->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
190           GNUNET_CRYPTO_RSA_KEY_LENGTH -
191           GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
192   gcry_mpi_release (skey[0]);
193   gcry_mpi_release (skey[1]);
194 }
195
196
197 /**
198  * Convert a public key to a string.
199  *
200  * @param pub key to convert
201  * @return string representing  'pub'
202  */
203 char *
204 GNUNET_CRYPTO_rsa_public_key_to_string (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
205 {
206   char *pubkeybuf;
207   size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
208   char *end;
209
210   if (keylen % 5 > 0)
211     keylen += 5 - keylen % 5;
212   keylen /= 5;
213   pubkeybuf = GNUNET_malloc (keylen + 1);
214   end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub, 
215                                        sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), 
216                                        pubkeybuf, 
217                                        keylen);
218   if (NULL == end)
219   {
220     GNUNET_free (pubkeybuf);
221     return NULL;
222   }
223   *end = '\0';
224   return pubkeybuf;
225 }
226
227
228 /**
229  * Convert a string representing a public key to a public key.
230  *
231  * @param enc encoded public key
232  * @param enclen number of bytes in enc (without 0-terminator)
233  * @param pub where to store the public key
234  * @return GNUNET_OK on success
235  */
236 int
237 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc, 
238                                           size_t enclen,
239                                           struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
240 {
241   size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
242
243   if (keylen % 5 > 0)
244     keylen += 5 - keylen % 5;
245   keylen /= 5;
246   if (enclen != keylen)
247     return GNUNET_SYSERR;
248
249   if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
250                                                  (unsigned char*) pub,
251                                                  sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
252     return GNUNET_SYSERR;
253   if ( (ntohs (pub->len) != sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) ||
254        (ntohs (pub->padding) != 0) ||
255        (ntohs (pub->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) )
256     return GNUNET_SYSERR;
257   return GNUNET_OK;
258 }
259
260
261 /**
262  * Internal: publicKey => RSA-Key.
263  *
264  * Note that the return type is not actually a private
265  * key but rather an sexpression for the public key!
266  */
267 static struct GNUNET_CRYPTO_RsaPrivateKey *
268 public2PrivateKey (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
269                    *publicKey)
270 {
271   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
272   gcry_sexp_t result;
273   gcry_mpi_t n;
274   gcry_mpi_t e;
275   size_t size;
276   size_t erroff;
277   int rc;
278
279   if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
280       (ntohs (publicKey->len) !=
281        sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
282        sizeof (publicKey->padding)))
283   {
284     GNUNET_break (0);
285     return NULL;
286   }
287   size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
288   rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
289   if (rc)
290   {
291     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
292     return NULL;
293   }
294   size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
295   rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
296                       &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
297                       size, &size);
298   if (rc)
299   {
300     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
301     gcry_mpi_release (n);
302     return NULL;
303   }
304   rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
305                         e);
306   gcry_mpi_release (n);
307   gcry_mpi_release (e);
308   if (rc)
309   {
310     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);  /* erroff gives more info */
311     return NULL;
312   }
313   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
314   ret->sexp = result;
315   return ret;
316 }
317
318
319 /**
320  * Encode the private key in a format suitable for
321  * storing it into a file.
322  * @returns encoding of the private key.
323  *    The first 4 bytes give the size of the array, as usual.
324  */
325 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
326 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
327 {
328   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *retval;
329   gcry_mpi_t pkv[6];
330   void *pbu[6];
331   size_t sizes[6];
332   int rc;
333   int i;
334   int size;
335
336 #if EXTRA_CHECKS
337   if (gcry_pk_testkey (hostkey->sexp))
338   {
339     GNUNET_break (0);
340     return NULL;
341   }
342 #endif
343
344   memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
345   rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
346   if (rc)
347     rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
348   if (rc)
349     rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
350   if (rc)
351     rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
352   if (rc)
353     rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
354   if (rc)
355     rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
356   GNUNET_assert (0 == rc);
357   size = sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded);
358   for (i = 0; i < 6; i++)
359   {
360     if (pkv[i] != NULL)
361     {
362       GNUNET_assert (0 ==
363                      gcry_mpi_aprint (GCRYMPI_FMT_USG,
364                                       (unsigned char **) &pbu[i], &sizes[i],
365                                       pkv[i]));
366       size += sizes[i];
367     }
368     else
369     {
370       pbu[i] = NULL;
371       sizes[i] = 0;
372     }
373   }
374   GNUNET_assert (size < 65536);
375   retval = GNUNET_malloc (size);
376   retval->len = htons (size);
377   i = 0;
378   retval->sizen = htons (sizes[0]);
379   memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
380   i += sizes[0];
381   retval->sizee = htons (sizes[1]);
382   memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
383   i += sizes[1];
384   retval->sized = htons (sizes[2]);
385   memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
386   i += sizes[2];
387   /* swap p and q! */
388   retval->sizep = htons (sizes[4]);
389   memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
390   i += sizes[4];
391   retval->sizeq = htons (sizes[3]);
392   memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
393   i += sizes[3];
394   retval->sizedmp1 = htons (0);
395   retval->sizedmq1 = htons (0);
396   memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
397   for (i = 0; i < 6; i++)
398   {
399     if (pkv[i] != NULL)
400       gcry_mpi_release (pkv[i]);
401     if (pbu[i] != NULL)
402       free (pbu[i]);
403   }
404   return retval;
405 }
406
407
408 /**
409  * Decode the private key from the file-format back
410  * to the "normal", internal format.
411  *
412  * @param buf the buffer where the private key data is stored
413  * @param len the length of the data in 'buffer'
414  */
415 struct GNUNET_CRYPTO_RsaPrivateKey *
416 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
417 {
418   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
419   const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *encoding =
420       (const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *) buf;
421   gcry_sexp_t res;
422   gcry_mpi_t n, e, d, p, q, u;
423   int rc;
424   size_t size;
425   int pos;
426   uint16_t enc_len;
427
428   enc_len = ntohs (encoding->len);
429   if (len != enc_len)
430     return NULL;
431
432   pos = 0;
433   size = ntohs (encoding->sizen);
434   rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
435                       &((const unsigned char *) (&encoding[1]))[pos], size,
436                       &size);
437   pos += ntohs (encoding->sizen);
438   if (rc)
439   {
440     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
441     return NULL;
442   }
443   size = ntohs (encoding->sizee);
444   rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
445                       &((const unsigned char *) (&encoding[1]))[pos], size,
446                       &size);
447   pos += ntohs (encoding->sizee);
448   if (rc)
449   {
450     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
451     gcry_mpi_release (n);
452     return NULL;
453   }
454   size = ntohs (encoding->sized);
455   rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
456                       &((const unsigned char *) (&encoding[1]))[pos], size,
457                       &size);
458   pos += ntohs (encoding->sized);
459   if (rc)
460   {
461     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
462     gcry_mpi_release (n);
463     gcry_mpi_release (e);
464     return NULL;
465   }
466   /* swap p and q! */
467   size = ntohs (encoding->sizep);
468   if (size > 0)
469   {
470     rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
471                         &((const unsigned char *) (&encoding[1]))[pos], size,
472                         &size);
473     pos += ntohs (encoding->sizep);
474     if (rc)
475     {
476       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
477       gcry_mpi_release (n);
478       gcry_mpi_release (e);
479       gcry_mpi_release (d);
480       return NULL;
481     }
482   }
483   else
484     q = NULL;
485   size = ntohs (encoding->sizeq);
486   if (size > 0)
487   {
488     rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
489                         &((const unsigned char *) (&encoding[1]))[pos], size,
490                         &size);
491     pos += ntohs (encoding->sizeq);
492     if (rc)
493     {
494       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
495       gcry_mpi_release (n);
496       gcry_mpi_release (e);
497       gcry_mpi_release (d);
498       if (q != NULL)
499         gcry_mpi_release (q);
500       return NULL;
501     }
502   }
503   else
504     p = NULL;
505   pos += ntohs (encoding->sizedmp1);
506   pos += ntohs (encoding->sizedmq1);
507   size =
508       ntohs (encoding->len) - sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded) - pos;
509   if (size > 0)
510   {
511     rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
512                         &((const unsigned char *) (&encoding[1]))[pos], size,
513                         &size);
514     if (rc)
515     {
516       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
517       gcry_mpi_release (n);
518       gcry_mpi_release (e);
519       gcry_mpi_release (d);
520       if (p != NULL)
521         gcry_mpi_release (p);
522       if (q != NULL)
523         gcry_mpi_release (q);
524       return NULL;
525     }
526   }
527   else
528     u = NULL;
529
530   if ((p != NULL) && (q != NULL) && (u != NULL))
531   {
532     rc = gcry_sexp_build (&res, &size,  /* erroff */
533                           "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
534                           n, e, d, p, q, u);
535   }
536   else
537   {
538     if ((p != NULL) && (q != NULL))
539     {
540       rc = gcry_sexp_build (&res, &size,        /* erroff */
541                             "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
542                             n, e, d, p, q);
543     }
544     else
545     {
546       rc = gcry_sexp_build (&res, &size,        /* erroff */
547                             "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
548     }
549   }
550   gcry_mpi_release (n);
551   gcry_mpi_release (e);
552   gcry_mpi_release (d);
553   if (p != NULL)
554     gcry_mpi_release (p);
555   if (q != NULL)
556     gcry_mpi_release (q);
557   if (u != NULL)
558     gcry_mpi_release (u);
559
560   if (rc)
561     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
562 #if EXTRA_CHECKS
563   if (gcry_pk_testkey (res))
564   {
565     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
566     return NULL;
567   }
568 #endif
569   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
570   ret->sexp = res;
571   return ret;
572 }
573
574
575 /**
576  * Create a new private key. Caller must free return value.
577  *
578  * @return fresh private key
579  */
580 static struct GNUNET_CRYPTO_RsaPrivateKey *
581 rsa_key_create ()
582 {
583   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
584   gcry_sexp_t s_key;
585   gcry_sexp_t s_keyparam;
586
587   GNUNET_assert (0 ==
588                  gcry_sexp_build (&s_keyparam, NULL,
589                                   "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
590                                   HOSTKEY_LEN));
591   GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
592   gcry_sexp_release (s_keyparam);
593 #if EXTRA_CHECKS
594   GNUNET_assert (0 == gcry_pk_testkey (s_key));
595 #endif
596   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
597   ret->sexp = s_key;
598   return ret;
599 }
600
601
602 /**
603  * Try to read the private key from the given file.
604  *
605  * @param filename file to read the key from
606  * @return NULL on error
607  */
608 static struct GNUNET_CRYPTO_RsaPrivateKey *
609 try_read_key (const char *filename)
610 {
611   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
612   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
613   struct GNUNET_DISK_FileHandle *fd;
614   OFF_T fs;
615   uint16_t len;
616
617   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
618     return NULL;
619
620   /* hostkey file exists already, read it! */
621   if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
622                                            GNUNET_DISK_PERM_NONE)))
623   {
624     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
625     return NULL;
626   }
627   if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
628   {
629     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
630     (void) GNUNET_DISK_file_close (fd);
631     return NULL;
632   }
633   if (0 == fs)
634   {
635     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
636     return NULL;
637   }
638   if (fs > UINT16_MAX)
639   {
640     LOG (GNUNET_ERROR_TYPE_ERROR,
641          _("File `%s' does not contain a valid private key (too long, %llu bytes).  Deleting it.\n"),   
642          filename,
643          (unsigned long long) fs);
644     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
645     if (0 != UNLINK (filename))    
646       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
647     return NULL;
648   }
649
650   enc = GNUNET_malloc (fs);
651   GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
652   len = ntohs (enc->len);
653   ret = NULL;
654   if ((len != fs) ||
655       (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
656   {
657     LOG (GNUNET_ERROR_TYPE_ERROR,
658          _("File `%s' does not contain a valid private key (failed decode, %llu bytes).  Deleting it.\n"),
659          filename,
660          (unsigned long long) fs);
661     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
662     if (0 != UNLINK (filename))    
663       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
664     GNUNET_free (enc);
665     return NULL;
666   }
667   GNUNET_free (enc);
668
669   GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
670   return ret;  
671 }
672
673
674 /**
675  * Wait for a short time (we're trying to lock a file or want
676  * to give another process a shot at finishing a disk write, etc.).
677  * Sleeps for 100ms (as that should be long enough for virtually all
678  * modern systems to context switch and allow another process to do
679  * some 'real' work).
680  */
681 static void
682 short_wait ()
683 {
684   struct GNUNET_TIME_Relative timeout;
685
686   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
687   (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
688 }
689
690
691 /**
692  * Create a new private key by reading it from a file.  If the
693  * files does not exist, create a new key and write it to the
694  * file.  Caller must free return value.  Note that this function
695  * can not guarantee that another process might not be trying
696  * the same operation on the same file at the same time.
697  * If the contents of the file
698  * are invalid the old file is deleted and a fresh key is
699  * created.
700  *
701  * @return new private key, NULL on error (for example,
702  *   permission denied)
703  */
704 struct GNUNET_CRYPTO_RsaPrivateKey *
705 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
706 {
707   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
708   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
709   uint16_t len;
710   struct GNUNET_DISK_FileHandle *fd;
711   unsigned int cnt;
712   int ec;
713   uint64_t fs;
714   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
715   struct GNUNET_PeerIdentity pid;
716
717   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
718     return NULL;
719   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
720   {
721     fd = GNUNET_DISK_file_open (filename,
722                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
723                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
724                                 GNUNET_DISK_PERM_USER_READ |
725                                 GNUNET_DISK_PERM_USER_WRITE);
726     if (NULL == fd)
727     {
728       if (errno == EEXIST)
729       {
730         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
731         {
732           /* must exist but not be accessible, fail for good! */
733           if (0 != ACCESS (filename, R_OK))
734             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
735           else
736             GNUNET_break (0);   /* what is going on!? */
737           return NULL;
738         }
739         continue;
740       }
741       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
742       return NULL;
743     }
744     cnt = 0;
745
746     while (GNUNET_YES !=
747            GNUNET_DISK_file_lock (fd, 0,
748                                   sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
749                                   GNUNET_YES))
750     {
751       short_wait ();
752       if (0 == ++cnt % 10)
753       {
754         ec = errno;
755         LOG (GNUNET_ERROR_TYPE_ERROR,
756              _("Could not acquire lock on file `%s': %s...\n"), filename,
757              STRERROR (ec));
758       }
759     }
760     LOG (GNUNET_ERROR_TYPE_INFO,
761          _("Creating a new private key.  This may take a while.\n"));
762     ret = rsa_key_create ();
763     GNUNET_assert (ret != NULL);
764     enc = GNUNET_CRYPTO_rsa_encode_key (ret);
765     GNUNET_assert (enc != NULL);
766     GNUNET_assert (ntohs (enc->len) ==
767                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
768     GNUNET_free (enc);
769
770     GNUNET_DISK_file_sync (fd);
771     if (GNUNET_YES !=
772         GNUNET_DISK_file_unlock (fd, 0,
773                                  sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
774       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
775     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
776     GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
777     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
778     LOG (GNUNET_ERROR_TYPE_INFO,
779          _("I am host `%s'.  Stored new private key in `%s'.\n"),
780          GNUNET_i2s (&pid), filename);
781     return ret;
782   }
783   /* hostkey file exists already, read it! */
784   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
785                               GNUNET_DISK_PERM_NONE);
786   if (NULL == fd)
787   {
788     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
789     return NULL;
790   }
791   cnt = 0;
792   while (1)
793   {
794     if (GNUNET_YES !=
795         GNUNET_DISK_file_lock (fd, 0,
796                                sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
797                                GNUNET_NO))
798     {
799       if (0 == ++cnt % 60)
800       {
801         ec = errno;
802         LOG (GNUNET_ERROR_TYPE_ERROR,
803              _("Could not acquire lock on file `%s': %s...\n"), filename,
804              STRERROR (ec));
805         LOG (GNUNET_ERROR_TYPE_ERROR,
806              _
807              ("This may be ok if someone is currently generating a hostkey.\n"));
808       }
809       short_wait ();
810       continue;
811     }
812     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
813     {
814       /* eh, what!? File we opened is now gone!? */
815       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
816       if (GNUNET_YES !=
817           GNUNET_DISK_file_unlock (fd, 0,
818                                    sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
819         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
820       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
821
822       return NULL;
823     }
824     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
825       fs = 0;
826     if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
827     {
828       /* maybe we got the read lock before the hostkey generating
829        * process had a chance to get the write lock; give it up! */
830       if (GNUNET_YES !=
831           GNUNET_DISK_file_unlock (fd, 0,
832                                    sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
833         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
834       if (0 == ++cnt % 10)
835       {
836         LOG (GNUNET_ERROR_TYPE_ERROR,
837              _
838              ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
839              filename, (unsigned int) fs,
840              (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
841         LOG (GNUNET_ERROR_TYPE_ERROR,
842              _
843              ("This may be ok if someone is currently generating a hostkey.\n"));
844       }
845       short_wait ();                /* wait a bit longer! */
846       continue;
847     }
848     break;
849   }
850   enc = GNUNET_malloc (fs);
851   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
852   len = ntohs (enc->len);
853   ret = NULL;
854   if ((len != fs) ||
855       (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
856   {
857     LOG (GNUNET_ERROR_TYPE_ERROR,
858          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
859          filename);
860     if (0 != UNLINK (filename))
861     {
862       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
863     }
864   }
865   GNUNET_free (enc);
866   if (GNUNET_YES !=
867       GNUNET_DISK_file_unlock (fd, 0,
868                                sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
869     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
870   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
871   if (ret != NULL)
872   {
873     GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
874     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
875     LOG (GNUNET_ERROR_TYPE_INFO,
876          _("I am host `%s'.  Read private key from `%s'.\n"), GNUNET_i2s (&pid),
877          filename);
878   }
879   return ret;
880 }
881
882
883 /**
884  * Handle to cancel private key generation and state for the
885  * key generation operation.
886  */
887 struct GNUNET_CRYPTO_RsaKeyGenerationContext
888 {
889   
890   /**
891    * Continuation to call upon completion.
892    */
893   GNUNET_CRYPTO_RsaKeyCallback cont;
894
895   /**
896    * Closure for 'cont'.
897    */
898   void *cont_cls;
899
900   /**
901    * Name of the file.
902    */
903   char *filename;
904
905   /**
906    * Handle to the helper process which does the key generation.
907    */ 
908   struct GNUNET_OS_Process *gnunet_rsa;
909   
910   /**
911    * Handle to 'stdout' of gnunet-rsa.  We 'read' on stdout to detect
912    * process termination (instead of messing with SIGCHLD).
913    */
914   struct GNUNET_DISK_PipeHandle *gnunet_rsa_out;
915
916   /**
917    * Location where we store the private key if it already existed.
918    * (if this is used, 'filename', 'gnunet_rsa' and 'gnunet_rsa_out' will
919    * not be used).
920    */
921   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
922   
923   /**
924    * Task reading from 'gnunet_rsa_out' to wait for process termination.
925    */
926   GNUNET_SCHEDULER_TaskIdentifier read_task;
927   
928 };
929
930
931 /**
932  * Task called upon shutdown or process termination of 'gnunet-rsa' during
933  * RSA key generation.  Check where we are and perform the appropriate
934  * action.
935  *
936  * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
937  * @param tc scheduler context
938  */
939 static void
940 check_key_generation_completion (void *cls,
941                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
942 {
943   struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
944   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
945
946   gc->read_task = GNUNET_SCHEDULER_NO_TASK;
947   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
948   {
949     gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
950     GNUNET_CRYPTO_rsa_key_create_stop (gc);
951     return;
952   }
953   GNUNET_assert (GNUNET_OK == 
954                  GNUNET_OS_process_wait (gc->gnunet_rsa));
955   GNUNET_OS_process_destroy (gc->gnunet_rsa);
956   gc->gnunet_rsa = NULL;
957   if (NULL == (pk = try_read_key (gc->filename)))
958   {
959     GNUNET_break (0);
960     gc->cont (gc->cont_cls, NULL, _("gnunet-rsa failed"));
961     GNUNET_CRYPTO_rsa_key_create_stop (gc);
962     return;
963   }
964   gc->cont (gc->cont_cls, pk, NULL);
965   GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
966   GNUNET_free (gc->filename);
967   GNUNET_free (gc);
968 }
969
970
971 /**
972  * Return the private RSA key which already existed on disk
973  * (asynchronously) to the caller.
974  *
975  * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
976  * @param tc scheduler context (unused)
977  */
978 static void
979 async_return_key (void *cls,
980                   const struct GNUNET_SCHEDULER_TaskContext *tc)
981 {
982   struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
983
984   gc->cont (gc->cont_cls,
985             gc->pk,
986             NULL);
987   GNUNET_free (gc);
988 }
989
990
991 /**
992  * Create a new private key by reading it from a file.  If the files
993  * does not exist, create a new key and write it to the file.  If the
994  * contents of the file are invalid the old file is deleted and a
995  * fresh key is created.
996  *
997  * @param filename name of file to use for storage
998  * @param cont function to call when done (or on errors)
999  * @param cont_cls closure for 'cont'
1000  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
1001  */
1002 struct GNUNET_CRYPTO_RsaKeyGenerationContext *
1003 GNUNET_CRYPTO_rsa_key_create_start (const char *filename,
1004                                     GNUNET_CRYPTO_RsaKeyCallback cont,
1005                                     void *cont_cls)
1006 {
1007   struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc;
1008   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1009   const char *weak_random;
1010
1011   if (NULL != (pk = try_read_key (filename)))
1012   {
1013     /* quick happy ending: key already exists! */
1014     gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1015     gc->pk = pk;
1016     gc->cont = cont;
1017     gc->cont_cls = cont_cls;
1018     gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
1019                                               gc);
1020     return gc;
1021   }
1022   gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1023   gc->filename = GNUNET_strdup (filename);
1024   gc->cont = cont;
1025   gc->cont_cls = cont_cls;
1026   gc->gnunet_rsa_out = GNUNET_DISK_pipe (GNUNET_NO,
1027                                          GNUNET_NO,
1028                                          GNUNET_NO,
1029                                          GNUNET_YES);
1030   if (NULL == gc->gnunet_rsa_out)
1031   {
1032     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
1033     GNUNET_free (gc->filename);
1034     GNUNET_free (gc);
1035     return NULL;
1036   }
1037   weak_random = NULL;
1038   if (GNUNET_YES ==
1039       GNUNET_CRYPTO_random_is_weak ())
1040     weak_random = "-w";
1041   gc->gnunet_rsa = GNUNET_OS_start_process (GNUNET_NO,
1042                                             GNUNET_OS_INHERIT_STD_ERR,
1043                                             NULL, 
1044                                             gc->gnunet_rsa_out,
1045                                             "gnunet-rsa",
1046                                             "gnunet-rsa",                                           
1047                                             gc->filename,
1048                                             weak_random,
1049                                             NULL);
1050   if (NULL == gc->gnunet_rsa)
1051   {
1052     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
1053     GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1054     GNUNET_free (gc->filename);
1055     GNUNET_free (gc);
1056     return NULL;
1057   }
1058   GNUNET_assert (GNUNET_OK ==
1059                  GNUNET_DISK_pipe_close_end (gc->gnunet_rsa_out,
1060                                              GNUNET_DISK_PIPE_END_WRITE));
1061   gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1062                                                   GNUNET_DISK_pipe_handle (gc->gnunet_rsa_out,
1063                                                                            GNUNET_DISK_PIPE_END_READ),
1064                                                   &check_key_generation_completion,
1065                                                   gc);
1066   return gc;
1067 }
1068
1069
1070 /**
1071  * Abort RSA key generation.
1072  *
1073  * @param gc key generation context to abort
1074  */
1075 void
1076 GNUNET_CRYPTO_rsa_key_create_stop (struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc)
1077 {
1078   if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
1079   {
1080     GNUNET_SCHEDULER_cancel (gc->read_task);
1081     gc->read_task = GNUNET_SCHEDULER_NO_TASK;
1082   }
1083   if (NULL != gc->gnunet_rsa)
1084   {
1085     (void) GNUNET_OS_process_kill (gc->gnunet_rsa, SIGKILL);
1086     GNUNET_break (GNUNET_OK ==
1087                   GNUNET_OS_process_wait (gc->gnunet_rsa));
1088     GNUNET_OS_process_destroy (gc->gnunet_rsa);
1089     GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1090   }
1091
1092   if (NULL != gc->filename)
1093   {
1094     if (0 != UNLINK (gc->filename))
1095       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
1096     GNUNET_free (gc->filename);
1097   }
1098   if (NULL != gc->pk)
1099     GNUNET_CRYPTO_rsa_key_free (gc->pk);
1100   GNUNET_free (gc);
1101 }
1102
1103
1104 /**
1105  * Setup a hostkey file for a peer given the name of the
1106  * configuration file (!).  This function is used so that
1107  * at a later point code can be certain that reading a
1108  * hostkey is fast (for example in time-dependent testcases).
1109  *
1110  * @param cfg_name name of the configuration file to use
1111  */
1112 void
1113 GNUNET_CRYPTO_setup_hostkey (const char *cfg_name)
1114 {
1115   struct GNUNET_CONFIGURATION_Handle *cfg;
1116   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1117   char *fn;
1118
1119   cfg = GNUNET_CONFIGURATION_create ();
1120   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
1121   if (GNUNET_OK == 
1122       GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
1123   {
1124     pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
1125     if (NULL != pk)
1126       GNUNET_CRYPTO_rsa_key_free (pk);
1127     GNUNET_free (fn);
1128   }
1129   GNUNET_CONFIGURATION_destroy (cfg);
1130 }
1131
1132
1133 /**
1134  * Encrypt a block with the public key of another host that uses the
1135  * same cipher.
1136  *
1137  * @param block the block to encrypt
1138  * @param size the size of block
1139  * @param publicKey the encoded public key used to encrypt
1140  * @param target where to store the encrypted block
1141  * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
1142  */
1143 int
1144 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
1145                            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1146                            *publicKey,
1147                            struct GNUNET_CRYPTO_RsaEncryptedData *target)
1148 {
1149   gcry_sexp_t result;
1150   gcry_sexp_t data;
1151   struct GNUNET_CRYPTO_RsaPrivateKey *pubkey;
1152   gcry_mpi_t val;
1153   gcry_mpi_t rval;
1154   size_t isize;
1155   size_t erroff;
1156
1157   GNUNET_assert (size <= sizeof (struct GNUNET_HashCode));
1158   pubkey = public2PrivateKey (publicKey);
1159   if (pubkey == NULL)
1160     return GNUNET_SYSERR;
1161   isize = size;
1162   GNUNET_assert (0 ==
1163                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
1164   GNUNET_assert (0 ==
1165                  gcry_sexp_build (&data, &erroff,
1166                                   "(data (flags pkcs1)(value %m))", val));
1167   gcry_mpi_release (val);
1168   GNUNET_assert (0 == gcry_pk_encrypt (&result, data, pubkey->sexp));
1169   gcry_sexp_release (data);
1170   GNUNET_CRYPTO_rsa_key_free (pubkey);
1171
1172   GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
1173   gcry_sexp_release (result);
1174   isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1175   GNUNET_assert (0 ==
1176                  gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
1177                                  isize, &isize, rval));
1178   gcry_mpi_release (rval);
1179   adjust (&target->encoding[0], isize,
1180           sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
1181   return GNUNET_OK;
1182 }
1183
1184
1185 /**
1186  * Decrypt a given block with the hostkey.
1187  *
1188  * @param key the key with which to decrypt this block
1189  * @param block the data to decrypt, encoded as returned by encrypt
1190  * @param result pointer to a location where the result can be stored
1191  * @param max the maximum number of bits to store for the result, if
1192  *        the decrypted block is bigger, an error is returned
1193  * @return the size of the decrypted block, -1 on error
1194  */
1195 ssize_t
1196 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
1197                            const struct GNUNET_CRYPTO_RsaEncryptedData * block,
1198                            void *result, size_t max)
1199 {
1200   gcry_sexp_t resultsexp;
1201   gcry_sexp_t data;
1202   size_t erroff;
1203   size_t size;
1204   gcry_mpi_t val;
1205   unsigned char *endp;
1206   unsigned char *tmp;
1207
1208 #if EXTRA_CHECKS
1209   GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
1210 #endif
1211   size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1212   GNUNET_assert (0 ==
1213                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
1214                                 size, &size));
1215   GNUNET_assert (0 ==
1216                  gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
1217                                   val));
1218   gcry_mpi_release (val);
1219   GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
1220   gcry_sexp_release (data);
1221   /* resultsexp has format "(value %m)" */
1222   GNUNET_assert (NULL !=
1223                  (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
1224   gcry_sexp_release (resultsexp);
1225   tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
1226   size = max + HOSTKEY_LEN / 8;
1227   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
1228   gcry_mpi_release (val);
1229   endp = tmp;
1230   endp += (size - max);
1231   size = max;
1232   memcpy (result, endp, size);
1233   GNUNET_free (tmp);
1234   return size;
1235 }
1236
1237
1238 /**
1239  * Sign a given block.
1240  *
1241  * @param key private key to use for the signing
1242  * @param purpose what to sign (size, purpose)
1243  * @param sig where to write the signature
1244  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1245  */
1246 int
1247 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1248                         const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
1249                         struct GNUNET_CRYPTO_RsaSignature *sig)
1250 {
1251   gcry_sexp_t result;
1252   gcry_sexp_t data;
1253   size_t ssize;
1254   gcry_mpi_t rval;
1255   struct GNUNET_HashCode hc;
1256   char *buff;
1257   int bufSize;
1258
1259   GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1260 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
1261   bufSize = strlen (FORMATSTRING) + 1;
1262   buff = GNUNET_malloc (bufSize);
1263   memcpy (buff, FORMATSTRING, bufSize);
1264   memcpy (&buff
1265           [bufSize -
1266            strlen
1267            ("0123456789012345678901234567890123456789012345678901234567890123))")
1268            - 1], &hc, sizeof (struct GNUNET_HashCode));
1269   GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1270   GNUNET_free (buff);
1271   GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
1272   gcry_sexp_release (data);
1273   GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
1274   gcry_sexp_release (result);
1275   ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1276   GNUNET_assert (0 ==
1277                  gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
1278                                  &ssize, rval));
1279   gcry_mpi_release (rval);
1280   adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
1281   return GNUNET_OK;
1282 }
1283
1284
1285 /**
1286  * Verify signature.
1287  *
1288  * @param purpose what is the purpose that the signature should have?
1289  * @param validate block to validate (size, purpose, data)
1290  * @param sig signature that is being validated
1291  * @param publicKey public key of the signer
1292  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1293  */
1294 int
1295 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
1296                           const struct GNUNET_CRYPTO_RsaSignaturePurpose
1297                           *validate,
1298                           const struct GNUNET_CRYPTO_RsaSignature *sig,
1299                           const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1300                           *publicKey)
1301 {
1302   gcry_sexp_t data;
1303   gcry_sexp_t sigdata;
1304   size_t size;
1305   gcry_mpi_t val;
1306   struct GNUNET_CRYPTO_RsaPrivateKey *hostkey;
1307   struct GNUNET_HashCode hc;
1308   char *buff;
1309   int bufSize;
1310   size_t erroff;
1311   int rc;
1312
1313   if (purpose != ntohl (validate->purpose))
1314     return GNUNET_SYSERR;       /* purpose mismatch */
1315   GNUNET_CRYPTO_hash (validate, ntohl (validate->size), &hc);
1316   size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1317   GNUNET_assert (0 ==
1318                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1319                                 (const unsigned char *) sig, size, &size));
1320   GNUNET_assert (0 ==
1321                  gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1322                                   val));
1323   gcry_mpi_release (val);
1324   bufSize = strlen (FORMATSTRING) + 1;
1325   buff = GNUNET_malloc (bufSize);
1326   memcpy (buff, FORMATSTRING, bufSize);
1327   memcpy (&buff
1328           [strlen (FORMATSTRING) -
1329            strlen
1330            ("0123456789012345678901234567890123456789012345678901234567890123))")],
1331           &hc, sizeof (struct GNUNET_HashCode));
1332   GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1333   GNUNET_free (buff);
1334   hostkey = public2PrivateKey (publicKey);
1335   if (hostkey == NULL)
1336   {
1337     gcry_sexp_release (data);
1338     gcry_sexp_release (sigdata);
1339     return GNUNET_SYSERR;
1340   }
1341   rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
1342   GNUNET_CRYPTO_rsa_key_free (hostkey);
1343   gcry_sexp_release (data);
1344   gcry_sexp_release (sigdata);
1345   if (rc)
1346   {
1347     LOG (GNUNET_ERROR_TYPE_WARNING,
1348          _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1349          __LINE__, gcry_strerror (rc));
1350     return GNUNET_SYSERR;
1351   }
1352   return GNUNET_OK;
1353 }
1354
1355
1356 /* end of crypto_rsa.c */