- fix
[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  * Open existing private key file and read it.  If the
710  * file does not exist, or the contents of the file are
711  * invalid, the function fails
712  * Caller must free returned value.
713  *
714  * @return a private key, NULL on error (for example,
715  *         permission denied) or when file does not exist or contains invalid
716  *         data.
717  */
718 struct GNUNET_CRYPTO_RsaPrivateKey *
719 GNUNET_CRYPTO_rsa_key_create_from_existing_file (const char *filename)
720 {
721   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
722   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
723   uint16_t len;
724   struct GNUNET_DISK_FileHandle *fd;
725   unsigned int cnt;
726   int ec;
727   uint64_t fs;
728   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
729   struct GNUNET_PeerIdentity pid;
730
731   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
732                               GNUNET_DISK_PERM_NONE);
733   if (NULL == fd)
734   {
735     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
736     return NULL;
737   }
738   cnt = 0;
739   while (1)
740   {
741     if (GNUNET_YES !=
742         GNUNET_DISK_file_lock (fd, 0,
743                                sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
744                                GNUNET_NO))
745     {
746       if (0 == ++cnt % 60)
747       {
748         ec = errno;
749         LOG (GNUNET_ERROR_TYPE_ERROR,
750              _("Could not acquire lock on file `%s': %s...\n"), filename,
751              STRERROR (ec));
752         LOG (GNUNET_ERROR_TYPE_ERROR,
753              _
754              ("This may be ok if someone is currently generating a private key.\n"));
755       }
756       short_wait ();
757       continue;
758     }
759     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
760     {
761       /* eh, what!? File we opened is now gone!? */
762       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
763       if (GNUNET_YES !=
764           GNUNET_DISK_file_unlock (fd, 0,
765                                    sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
766         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
767       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
768
769       return NULL;
770     }
771     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
772       fs = 0;
773     if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
774     {
775       /* maybe we got the read lock before the key generating
776        * process had a chance to get the write lock; give it up! */
777       if (GNUNET_YES !=
778           GNUNET_DISK_file_unlock (fd, 0,
779                                    sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
780         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
781       if (0 == ++cnt % 10)
782       {
783         LOG (GNUNET_ERROR_TYPE_ERROR,
784              _
785              ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
786              filename, (unsigned int) fs,
787              (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
788         LOG (GNUNET_ERROR_TYPE_ERROR,
789              _
790              ("This may be ok if someone is currently generating a private key.\n"));
791       }
792       short_wait ();                /* wait a bit longer! */
793       continue;
794     }
795     break;
796   }
797   enc = GNUNET_malloc (fs);
798   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
799   len = ntohs (enc->len);
800   ret = NULL;
801   if ((len != fs) ||
802       (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
803   {
804     LOG (GNUNET_ERROR_TYPE_ERROR,
805          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
806          filename);
807     GNUNET_DISK_file_backup (filename);
808   }
809   GNUNET_free (enc);
810   if (GNUNET_YES !=
811       GNUNET_DISK_file_unlock (fd, 0,
812                                sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
813     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
814   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
815   if (ret != NULL)
816   {
817     GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
818     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
819   }
820   return ret;
821 }
822
823 /**
824  * Create a new private key by reading it from a file.  If the
825  * files does not exist, create a new key and write it to the
826  * file.  Caller must free return value.  Note that this function
827  * can not guarantee that another process might not be trying
828  * the same operation on the same file at the same time.
829  * If the contents of the file
830  * are invalid the old file is deleted and a fresh key is
831  * created.
832  *
833  * @return new private key, NULL on error (for example,
834  *   permission denied)
835  */
836 struct GNUNET_CRYPTO_RsaPrivateKey *
837 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
838 {
839   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
840   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
841   struct GNUNET_DISK_FileHandle *fd;
842   unsigned int cnt;
843   int ec;
844   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
845   struct GNUNET_PeerIdentity pid;
846
847   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
848     return NULL;
849
850   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
851   {
852     fd = GNUNET_DISK_file_open (filename,
853                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
854                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
855                                 GNUNET_DISK_PERM_USER_READ |
856                                 GNUNET_DISK_PERM_USER_WRITE);
857     if (NULL == fd)
858     {
859       if (EEXIST == errno)
860       {
861         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
862         {
863           /* must exist but not be accessible, fail for good! */
864           if (0 != ACCESS (filename, R_OK))
865             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
866           else
867             GNUNET_break (0);   /* what is going on!? */
868           return NULL;
869         }
870         continue;
871       }
872       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
873       return NULL;
874     }
875     cnt = 0;
876
877     while (GNUNET_YES !=
878            GNUNET_DISK_file_lock (fd, 0,
879                                   sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
880                                   GNUNET_YES))
881     {
882       short_wait ();
883       if (0 == ++cnt % 10)
884       {
885         ec = errno;
886         LOG (GNUNET_ERROR_TYPE_ERROR,
887              _("Could not acquire lock on file `%s': %s...\n"), filename,
888              STRERROR (ec));
889       }
890     }
891     LOG (GNUNET_ERROR_TYPE_INFO,
892          _("Creating a new private key.  This may take a while.\n"));
893     ret = rsa_key_create ();
894     GNUNET_assert (ret != NULL);
895     enc = GNUNET_CRYPTO_rsa_encode_key (ret);
896     GNUNET_assert (enc != NULL);
897     GNUNET_assert (ntohs (enc->len) ==
898                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
899     GNUNET_free (enc);
900
901     GNUNET_DISK_file_sync (fd);
902     if (GNUNET_YES !=
903         GNUNET_DISK_file_unlock (fd, 0,
904                                  sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
905       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
906     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
907     GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
908     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
909     return ret;
910   }
911   /* hostkey file exists already, read it! */
912   return GNUNET_CRYPTO_rsa_key_create_from_existing_file (filename);
913 }
914
915
916 /**
917  * Handle to cancel private key generation and state for the
918  * key generation operation.
919  */
920 struct GNUNET_CRYPTO_RsaKeyGenerationContext
921 {
922   
923   /**
924    * Continuation to call upon completion.
925    */
926   GNUNET_CRYPTO_RsaKeyCallback cont;
927
928   /**
929    * Closure for 'cont'.
930    */
931   void *cont_cls;
932
933   /**
934    * Name of the file.
935    */
936   char *filename;
937
938   /**
939    * Handle to the helper process which does the key generation.
940    */ 
941   struct GNUNET_OS_Process *gnunet_rsa;
942   
943   /**
944    * Handle to 'stdout' of gnunet-rsa.  We 'read' on stdout to detect
945    * process termination (instead of messing with SIGCHLD).
946    */
947   struct GNUNET_DISK_PipeHandle *gnunet_rsa_out;
948
949   /**
950    * Location where we store the private key if it already existed.
951    * (if this is used, 'filename', 'gnunet_rsa' and 'gnunet_rsa_out' will
952    * not be used).
953    */
954   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
955   
956   /**
957    * Task reading from 'gnunet_rsa_out' to wait for process termination.
958    */
959   GNUNET_SCHEDULER_TaskIdentifier read_task;
960   
961 };
962
963
964 /**
965  * Task called upon shutdown or process termination of 'gnunet-rsa' during
966  * RSA key generation.  Check where we are and perform the appropriate
967  * action.
968  *
969  * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
970  * @param tc scheduler context
971  */
972 static void
973 check_key_generation_completion (void *cls,
974                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
975 {
976   struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
977   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
978
979   gc->read_task = GNUNET_SCHEDULER_NO_TASK;
980   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
981   {
982     gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
983     GNUNET_CRYPTO_rsa_key_create_stop (gc);
984     return;
985   }
986   GNUNET_assert (GNUNET_OK == 
987                  GNUNET_OS_process_wait (gc->gnunet_rsa));
988   GNUNET_OS_process_destroy (gc->gnunet_rsa);
989   gc->gnunet_rsa = NULL;
990   if (NULL == (pk = try_read_key (gc->filename)))
991   {
992     GNUNET_break (0);
993     gc->cont (gc->cont_cls, NULL, _("gnunet-rsa failed"));
994     GNUNET_CRYPTO_rsa_key_create_stop (gc);
995     return;
996   }
997   gc->cont (gc->cont_cls, pk, NULL);
998   GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
999   GNUNET_free (gc->filename);
1000   GNUNET_free (gc);
1001 }
1002
1003
1004 /**
1005  * Return the private RSA key which already existed on disk
1006  * (asynchronously) to the caller.
1007  *
1008  * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
1009  * @param tc scheduler context (unused)
1010  */
1011 static void
1012 async_return_key (void *cls,
1013                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1014 {
1015   struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
1016
1017   gc->cont (gc->cont_cls,
1018             gc->pk,
1019             NULL);
1020   GNUNET_free (gc);
1021 }
1022
1023
1024 /**
1025  * Create a new private key by reading it from a file.  If the files
1026  * does not exist, create a new key and write it to the file.  If the
1027  * contents of the file are invalid the old file is deleted and a
1028  * fresh key is created.
1029  *
1030  * @param filename name of file to use for storage
1031  * @param cont function to call when done (or on errors)
1032  * @param cont_cls closure for 'cont'
1033  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
1034  */
1035 struct GNUNET_CRYPTO_RsaKeyGenerationContext *
1036 GNUNET_CRYPTO_rsa_key_create_start (const char *filename,
1037                                     GNUNET_CRYPTO_RsaKeyCallback cont,
1038                                     void *cont_cls)
1039 {
1040   struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc;
1041   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1042
1043   if (NULL != (pk = try_read_key (filename)))
1044   {
1045     /* quick happy ending: key already exists! */
1046     gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1047     gc->pk = pk;
1048     gc->cont = cont;
1049     gc->cont_cls = cont_cls;
1050     gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
1051                                               gc);
1052     return gc;
1053   }
1054   gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1055   gc->filename = GNUNET_strdup (filename);
1056   gc->cont = cont;
1057   gc->cont_cls = cont_cls;
1058   gc->gnunet_rsa_out = GNUNET_DISK_pipe (GNUNET_NO,
1059                                          GNUNET_NO,
1060                                          GNUNET_NO,
1061                                          GNUNET_YES);
1062   if (NULL == gc->gnunet_rsa_out)
1063   {
1064     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
1065     GNUNET_free (gc->filename);
1066     GNUNET_free (gc);
1067     return NULL;
1068   }
1069   gc->gnunet_rsa = GNUNET_OS_start_process (GNUNET_NO,
1070                                             GNUNET_OS_INHERIT_STD_ERR,
1071                                             NULL, 
1072                                             gc->gnunet_rsa_out,
1073                                             "gnunet-rsa",
1074                                             "gnunet-rsa",                                           
1075                                             gc->filename,
1076                                             NULL);
1077   if (NULL == gc->gnunet_rsa)
1078   {
1079     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
1080     GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1081     GNUNET_free (gc->filename);
1082     GNUNET_free (gc);
1083     return NULL;
1084   }
1085   GNUNET_assert (GNUNET_OK ==
1086                  GNUNET_DISK_pipe_close_end (gc->gnunet_rsa_out,
1087                                              GNUNET_DISK_PIPE_END_WRITE));
1088   gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1089                                                   GNUNET_DISK_pipe_handle (gc->gnunet_rsa_out,
1090                                                                            GNUNET_DISK_PIPE_END_READ),
1091                                                   &check_key_generation_completion,
1092                                                   gc);
1093   return gc;
1094 }
1095
1096
1097 /**
1098  * Abort RSA key generation.
1099  *
1100  * @param gc key generation context to abort
1101  */
1102 void
1103 GNUNET_CRYPTO_rsa_key_create_stop (struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc)
1104 {
1105   if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
1106   {
1107     GNUNET_SCHEDULER_cancel (gc->read_task);
1108     gc->read_task = GNUNET_SCHEDULER_NO_TASK;
1109   }
1110   if (NULL != gc->gnunet_rsa)
1111   {
1112     (void) GNUNET_OS_process_kill (gc->gnunet_rsa, SIGKILL);
1113     GNUNET_break (GNUNET_OK ==
1114                   GNUNET_OS_process_wait (gc->gnunet_rsa));
1115     GNUNET_OS_process_destroy (gc->gnunet_rsa);
1116     GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1117   }
1118
1119   if (NULL != gc->filename)
1120   {
1121     if (0 != UNLINK (gc->filename))
1122       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
1123     GNUNET_free (gc->filename);
1124   }
1125   if (NULL != gc->pk)
1126     GNUNET_CRYPTO_rsa_key_free (gc->pk);
1127   GNUNET_free (gc);
1128 }
1129
1130
1131 /**
1132  * Setup a key file for a peer given the name of the
1133  * configuration file (!).  This function is used so that
1134  * at a later point code can be certain that reading a
1135  * key is fast (for example in time-dependent testcases).
1136  *
1137  * @param cfg_name name of the configuration file to use
1138  */
1139 void
1140 GNUNET_CRYPTO_rsa_setup_hostkey (const char *cfg_name)
1141 {
1142   struct GNUNET_CONFIGURATION_Handle *cfg;
1143   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1144   char *fn;
1145
1146   cfg = GNUNET_CONFIGURATION_create ();
1147   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
1148   if (GNUNET_OK == 
1149       GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
1150   {
1151     pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
1152     if (NULL != pk)
1153       GNUNET_CRYPTO_rsa_key_free (pk);
1154     GNUNET_free (fn);
1155   }
1156   GNUNET_CONFIGURATION_destroy (cfg);
1157 }
1158
1159
1160 /**
1161  * Encrypt a block with the public key of another host that uses the
1162  * same cipher.
1163  *
1164  * @param block the block to encrypt
1165  * @param size the size of block
1166  * @param publicKey the encoded public key used to encrypt
1167  * @param target where to store the encrypted block
1168  * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
1169  */
1170 int
1171 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
1172                            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1173                            *publicKey,
1174                            struct GNUNET_CRYPTO_RsaEncryptedData *target)
1175 {
1176   gcry_sexp_t result;
1177   gcry_sexp_t data;
1178   gcry_sexp_t psexp;
1179   gcry_mpi_t val;
1180   gcry_mpi_t rval;
1181   size_t isize;
1182   size_t erroff;
1183
1184   GNUNET_assert (size <= sizeof (struct GNUNET_HashCode));
1185   if (! (psexp = decode_public_key (publicKey)))
1186     return GNUNET_SYSERR;
1187   isize = size;
1188   GNUNET_assert (0 ==
1189                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
1190   GNUNET_assert (0 ==
1191                  gcry_sexp_build (&data, &erroff,
1192                                   "(data (flags pkcs1)(value %m))", val));
1193   gcry_mpi_release (val);
1194   GNUNET_assert (0 == gcry_pk_encrypt (&result, data, psexp));
1195   gcry_sexp_release (data);
1196   gcry_sexp_release (psexp);
1197   GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
1198   gcry_sexp_release (result);
1199   isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1200   GNUNET_assert (0 ==
1201                  gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
1202                                  isize, &isize, rval));
1203   gcry_mpi_release (rval);
1204   adjust (&target->encoding[0], isize,
1205           sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
1206   return GNUNET_OK;
1207 }
1208
1209
1210 /**
1211  * Decrypt a given block with the key.
1212  *
1213  * @param key the key with which to decrypt this block
1214  * @param block the data to decrypt, encoded as returned by encrypt
1215  * @param result pointer to a location where the result can be stored
1216  * @param max the maximum number of bits to store for the result, if
1217  *        the decrypted block is bigger, an error is returned
1218  * @return the size of the decrypted block, -1 on error
1219  */
1220 ssize_t
1221 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
1222                            const struct GNUNET_CRYPTO_RsaEncryptedData * block,
1223                            void *result, size_t max)
1224 {
1225   gcry_sexp_t resultsexp;
1226   gcry_sexp_t data;
1227   size_t erroff;
1228   size_t size;
1229   gcry_mpi_t val;
1230   unsigned char *endp;
1231   unsigned char *tmp;
1232
1233 #if EXTRA_CHECKS
1234   GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
1235 #endif
1236   size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1237   GNUNET_assert (0 ==
1238                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
1239                                 size, &size));
1240   GNUNET_assert (0 ==
1241                  gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
1242                                   val));
1243   gcry_mpi_release (val);
1244   GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
1245   gcry_sexp_release (data);
1246   /* resultsexp has format "(value %m)" */
1247   GNUNET_assert (NULL !=
1248                  (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
1249   gcry_sexp_release (resultsexp);
1250   tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
1251   size = max + HOSTKEY_LEN / 8;
1252   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
1253   gcry_mpi_release (val);
1254   endp = tmp;
1255   endp += (size - max);
1256   size = max;
1257   memcpy (result, endp, size);
1258   GNUNET_free (tmp);
1259   return size;
1260 }
1261
1262
1263 /**
1264  * Convert the data specified in the given purpose argument to an
1265  * S-expression suitable for signature operations.
1266  *
1267  * @param purpose data to convert
1268  * @return converted s-expression
1269  */
1270 static gcry_sexp_t
1271 data_to_pkcs1 (const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose)
1272 {
1273   struct GNUNET_HashCode hc;
1274   size_t bufSize;
1275   gcry_sexp_t data;
1276
1277   GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1278 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
1279   bufSize = strlen (FORMATSTRING) + 1;
1280   {
1281     char buff[bufSize];
1282
1283     memcpy (buff, FORMATSTRING, bufSize);
1284     memcpy (&buff
1285             [bufSize -
1286              strlen
1287              ("0123456789012345678901234567890123456789012345678901234567890123))")
1288              - 1], &hc, sizeof (struct GNUNET_HashCode));
1289     GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1290   }
1291 #undef FORMATSTRING
1292   return data;
1293 }
1294
1295
1296 /**
1297  * Sign a given block.
1298  *
1299  * @param key private key to use for the signing
1300  * @param purpose what to sign (size, purpose)
1301  * @param sig where to write the signature
1302  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1303  */
1304 int
1305 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1306                         const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
1307                         struct GNUNET_CRYPTO_RsaSignature *sig)
1308 {
1309   gcry_sexp_t result;
1310   gcry_sexp_t data;
1311   size_t ssize;
1312   gcry_mpi_t rval;
1313
1314   data = data_to_pkcs1 (purpose);
1315   GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
1316   gcry_sexp_release (data);
1317   GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
1318   gcry_sexp_release (result);
1319   ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1320   GNUNET_assert (0 ==
1321                  gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
1322                                  &ssize, rval));
1323   gcry_mpi_release (rval);
1324   adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
1325   return GNUNET_OK;
1326 }
1327
1328
1329 /**
1330  * Verify signature.
1331  *
1332  * @param purpose what is the purpose that the signature should have?
1333  * @param validate block to validate (size, purpose, data)
1334  * @param sig signature that is being validated
1335  * @param publicKey public key of the signer
1336  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1337  */
1338 int
1339 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
1340                           const struct GNUNET_CRYPTO_RsaSignaturePurpose
1341                           *validate,
1342                           const struct GNUNET_CRYPTO_RsaSignature *sig,
1343                           const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1344                           *publicKey)
1345 {
1346   gcry_sexp_t data;
1347   gcry_sexp_t sigdata;
1348   size_t size;
1349   gcry_mpi_t val;
1350   gcry_sexp_t psexp;
1351   size_t erroff;
1352   int rc;
1353
1354   if (purpose != ntohl (validate->purpose))
1355     return GNUNET_SYSERR;       /* purpose mismatch */
1356   size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1357   GNUNET_assert (0 ==
1358                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1359                                 (const unsigned char *) sig, size, &size));
1360   GNUNET_assert (0 ==
1361                  gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1362                                   val));
1363   gcry_mpi_release (val);
1364   data = data_to_pkcs1 (validate);
1365   if (! (psexp = decode_public_key (publicKey)))
1366   {
1367     gcry_sexp_release (data);
1368     gcry_sexp_release (sigdata);
1369     return GNUNET_SYSERR;
1370   }
1371   rc = gcry_pk_verify (sigdata, data, psexp);
1372   gcry_sexp_release (psexp);
1373   gcry_sexp_release (data);
1374   gcry_sexp_release (sigdata);
1375   if (rc)
1376   {
1377     LOG (GNUNET_ERROR_TYPE_WARNING,
1378          _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1379          __LINE__, gcry_strerror (rc));
1380     return GNUNET_SYSERR;
1381   }
1382   return GNUNET_OK;
1383 }
1384
1385
1386 /* end of crypto_rsa.c */