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