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