fixing symbol naming and coding convention issues
[oweals/gnunet.git] / src / util / crypto_rsa.c
1 /*
2   This file is part of GNUnet
3   Copyright (C) 2014 GNUnet e.V.
4
5   GNUnet is free software; you can redistribute it and/or modify it under the
6   terms of the GNU General Public License as published by the Free Software
7   Foundation; either version 3, or (at your option) any later version.
8
9   GNUnet is distributed in the hope that it will be useful, but WITHOUT ANY
10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
11   A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
12
13   You should have received a copy of the GNU General Public License along with
14   GNUnet; see the file COPYING.  If not, If not, see <http://www.gnu.org/licenses/>
15 */
16
17 /**
18  * @file util/crypto_rsa.c
19  * @brief Chaum-style Blind signatures based on RSA
20  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
21  * @author Christian Grothoff
22  */
23 #include "platform.h"
24 #include <gcrypt.h>
25 #include "gnunet_crypto_lib.h"
26
27 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
28
29
30 /**
31  * The private information of an RSA key pair.
32  */
33 struct GNUNET_CRYPTO_RsaPrivateKey
34 {
35   /**
36    * Libgcrypt S-expression for the RSA private key.
37    */
38   gcry_sexp_t sexp;
39 };
40
41
42 /**
43  * The public information of an RSA key pair.
44  */
45 struct GNUNET_CRYPTO_RsaPublicKey
46 {
47   /**
48    * Libgcrypt S-expression for the RSA public key.
49    */
50   gcry_sexp_t sexp;
51 };
52
53
54 /**
55  * @brief an RSA signature
56  */
57 struct GNUNET_CRYPTO_RsaSignature
58 {
59   /**
60    * Libgcrypt S-expression for the RSA signature.
61    */
62   gcry_sexp_t sexp;
63 };
64
65
66 /**
67  * @brief RSA blinding key
68  */
69 struct GNUNET_CRYPTO_rsa_BlindingKey
70 {
71   /**
72    * Random value used for blinding.
73    */
74   gcry_mpi_t r;
75 };
76
77
78 /**
79  * Extract values from an S-expression.
80  *
81  * @param array where to store the result(s)
82  * @param sexp S-expression to parse
83  * @param topname top-level name in the S-expression that is of interest
84  * @param elems names of the elements to extract
85  * @return 0 on success
86  */
87 static int
88 key_from_sexp (gcry_mpi_t *array,
89                gcry_sexp_t sexp,
90                const char *topname,
91                const char *elems)
92 {
93   gcry_sexp_t list;
94   gcry_sexp_t l2;
95   const char *s;
96   unsigned int i;
97   unsigned int idx;
98
99   if (! (list = gcry_sexp_find_token (sexp, topname, 0)))
100     return 1;
101   l2 = gcry_sexp_cadr (list);
102   gcry_sexp_release (list);
103   list = l2;
104   if (! list)
105     return 2;
106   idx = 0;
107   for (s = elems; *s; s++, idx++)
108   {
109     if (! (l2 = gcry_sexp_find_token (list, s, 1)))
110     {
111       for (i = 0; i < idx; i++)
112       {
113         gcry_free (array[i]);
114         array[i] = NULL;
115       }
116       gcry_sexp_release (list);
117       return 3;                 /* required parameter not found */
118     }
119     array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
120     gcry_sexp_release (l2);
121     if (! array[idx])
122     {
123       for (i = 0; i < idx; i++)
124       {
125         gcry_free (array[i]);
126         array[i] = NULL;
127       }
128       gcry_sexp_release (list);
129       return 4;                 /* required parameter is invalid */
130     }
131   }
132   gcry_sexp_release (list);
133   return 0;
134 }
135
136
137 /**
138  * Create a new private key. Caller must free return value.
139  *
140  * @param len length of the key in bits (i.e. 2048)
141  * @return fresh private key
142  */
143 struct GNUNET_CRYPTO_RsaPrivateKey *
144 GNUNET_CRYPTO_rsa_private_key_create (unsigned int len)
145 {
146   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
147   gcry_sexp_t s_key;
148   gcry_sexp_t s_keyparam;
149
150   GNUNET_assert (0 ==
151                  gcry_sexp_build (&s_keyparam,
152                                   NULL,
153                                   "(genkey(rsa(nbits %d)))",
154                                   len));
155   GNUNET_assert (0 ==
156                  gcry_pk_genkey (&s_key,
157                                  s_keyparam));
158   gcry_sexp_release (s_keyparam);
159 #if EXTRA_CHECKS
160   GNUNET_assert (0 ==
161                  gcry_pk_testkey (s_key));
162 #endif
163   ret = GNUNET_new (struct GNUNET_CRYPTO_RsaPrivateKey);
164   ret->sexp = s_key;
165   return ret;
166 }
167
168
169 /**
170  * Free memory occupied by the private key.
171  *
172  * @param key pointer to the memory to free
173  */
174 void
175 GNUNET_CRYPTO_rsa_private_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *key)
176 {
177   gcry_sexp_release (key->sexp);
178   GNUNET_free (key);
179 }
180
181
182 /**
183  * Encode the private key in a format suitable for
184  * storing it into a file.
185  *
186  * @param key the private key
187  * @param[out] buffer set to a buffer with the encoded key
188  * @return size of memory allocated in @a buffer
189  */
190 size_t
191 GNUNET_CRYPTO_rsa_private_key_encode (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
192                                       char **buffer)
193 {
194   size_t n;
195   char *b;
196
197   n = gcry_sexp_sprint (key->sexp,
198                         GCRYSEXP_FMT_DEFAULT,
199                         NULL,
200                         0);
201   b = GNUNET_malloc (n);
202   GNUNET_assert ((n - 1) ==     /* since the last byte is \0 */
203                  gcry_sexp_sprint (key->sexp,
204                                    GCRYSEXP_FMT_DEFAULT,
205                                    b,
206                                    n));
207   *buffer = b;
208   return n;
209 }
210
211
212 /**
213  * Decode the private key from the data-format back
214  * to the "normal", internal format.
215  *
216  * @param buf the buffer where the private key data is stored
217  * @param len the length of the data in @a buf
218  * @return NULL on error
219  */
220 struct GNUNET_CRYPTO_RsaPrivateKey *
221 GNUNET_CRYPTO_rsa_private_key_decode (const char *buf,
222                                       size_t len)
223 {
224   struct GNUNET_CRYPTO_RsaPrivateKey *key;
225   key = GNUNET_new (struct GNUNET_CRYPTO_RsaPrivateKey);
226   if (0 !=
227       gcry_sexp_new (&key->sexp,
228                      buf,
229                      len,
230                      0))
231   {
232     LOG (GNUNET_ERROR_TYPE_WARNING,
233          "Decoded private key is not valid\n");
234     GNUNET_free (key);
235     return NULL;
236   }
237   if (0 != gcry_pk_testkey (key->sexp))
238   {
239     LOG (GNUNET_ERROR_TYPE_WARNING,
240          "Decoded private key is not valid\n");
241     GNUNET_CRYPTO_rsa_private_key_free (key);
242     return NULL;
243   }
244   return key;
245 }
246
247
248 /**
249  * Extract the public key of the given private key.
250  *
251  * @param priv the private key
252  * @retur NULL on error, otherwise the public key
253  */
254 struct GNUNET_CRYPTO_RsaPublicKey *
255 GNUNET_CRYPTO_rsa_private_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey *priv)
256 {
257   struct GNUNET_CRYPTO_RsaPublicKey *pub;
258   gcry_mpi_t ne[2];
259   int rc;
260   gcry_sexp_t result;
261
262   rc = key_from_sexp (ne, priv->sexp, "public-key", "ne");
263   if (0 != rc)
264     rc = key_from_sexp (ne, priv->sexp, "private-key", "ne");
265   if (0 != rc)
266     rc = key_from_sexp (ne, priv->sexp, "rsa", "ne");
267   if (0 != rc)
268   {
269     GNUNET_break_op (0);
270     return NULL;
271   }
272   rc = gcry_sexp_build (&result,
273                         NULL,
274                         "(public-key(rsa(n %m)(e %m)))",
275                         ne[0],
276                         ne[1]);
277   gcry_mpi_release (ne[0]);
278   gcry_mpi_release (ne[1]);
279   pub = GNUNET_new (struct GNUNET_CRYPTO_RsaPublicKey);
280   pub->sexp = result;
281   return pub;
282 }
283
284
285 /**
286  * Free memory occupied by the public key.
287  *
288  * @param key pointer to the memory to free
289  */
290 void
291 GNUNET_CRYPTO_rsa_public_key_free (struct GNUNET_CRYPTO_RsaPublicKey *key)
292 {
293   gcry_sexp_release (key->sexp);
294   GNUNET_free (key);
295 }
296
297
298 /**
299  * Encode the public key in a format suitable for
300  * storing it into a file.
301  *
302  * @param key the private key
303  * @param[out] buffer set to a buffer with the encoded key
304  * @return size of memory allocated in @a buffer
305  */
306 size_t
307 GNUNET_CRYPTO_rsa_public_key_encode (const struct GNUNET_CRYPTO_RsaPublicKey *key,
308                                      char **buffer)
309 {
310   size_t n;
311   char *b;
312
313   n = gcry_sexp_sprint (key->sexp,
314                         GCRYSEXP_FMT_ADVANCED,
315                         NULL,
316                         0);
317   b = GNUNET_malloc (n);
318   GNUNET_assert ((n -1) ==      /* since the last byte is \0 */
319                  gcry_sexp_sprint (key->sexp,
320                                    GCRYSEXP_FMT_ADVANCED,
321                                    b,
322                                    n));
323   *buffer = b;
324   return n;
325 }
326
327
328 /**
329  * Compute hash over the public key.
330  *
331  * @param key public key to hash
332  * @param hc where to store the hash code
333  */
334 void
335 GNUNET_CRYPTO_rsa_public_key_hash (const struct GNUNET_CRYPTO_RsaPublicKey *key,
336                                    struct GNUNET_HashCode *hc)
337 {
338   char *buf;
339   size_t buf_size;
340
341   buf_size = GNUNET_CRYPTO_rsa_public_key_encode (key,
342                                                   &buf);
343   GNUNET_CRYPTO_hash (buf,
344                       buf_size,
345                       hc);
346   GNUNET_free (buf);
347 }
348
349
350 /**
351  * Decode the public key from the data-format back
352  * to the "normal", internal format.
353  *
354  * @param buf the buffer where the public key data is stored
355  * @param len the length of the data in @a buf
356  * @return NULL on error
357  */
358 struct GNUNET_CRYPTO_RsaPublicKey *
359 GNUNET_CRYPTO_rsa_public_key_decode (const char *buf,
360                                      size_t len)
361 {
362   struct GNUNET_CRYPTO_RsaPublicKey *key;
363   gcry_mpi_t n;
364   int ret;
365
366   key = GNUNET_new (struct GNUNET_CRYPTO_RsaPublicKey);
367   if (0 !=
368       gcry_sexp_new (&key->sexp,
369                      buf,
370                      len,
371                      0))
372   {
373     GNUNET_break_op (0);
374     GNUNET_free (key);
375     return NULL;
376   }
377   /* verify that this is an RSA public key */
378   ret = key_from_sexp (&n, key->sexp, "public-key", "n");
379   if (0 != ret)
380     ret = key_from_sexp (&n, key->sexp, "rsa", "n");
381   if (0 != ret)
382   {
383     /* this is no public RSA key */
384     GNUNET_break (0);
385     gcry_sexp_release (key->sexp);
386     GNUNET_free (key);
387     return NULL;
388   }
389   gcry_mpi_release (n);
390   return key;
391 }
392
393
394 /**
395  * Create a blinding key
396  *
397  * @param len length of the key in bits (i.e. 2048)
398  * @return the newly created blinding key
399  */
400 struct GNUNET_CRYPTO_rsa_BlindingKey *
401 GNUNET_CRYPTO_rsa_blinding_key_create (unsigned int len)
402 {
403   struct GNUNET_CRYPTO_rsa_BlindingKey *blind;
404
405   blind = GNUNET_new (struct GNUNET_CRYPTO_rsa_BlindingKey);
406   blind->r = gcry_mpi_new (len);
407   gcry_mpi_randomize (blind->r,
408                       len,
409                       GCRY_STRONG_RANDOM);
410   return blind;
411 }
412
413
414 /**
415  * Compare the values of two blinding keys.
416  *
417  * @param b1 one key
418  * @param b2 the other key
419  * @return 0 if the two are equal
420  */
421 int
422 GNUNET_CRYPTO_rsa_blinding_key_cmp (struct GNUNET_CRYPTO_rsa_BlindingKey *b1,
423                                     struct GNUNET_CRYPTO_rsa_BlindingKey *b2)
424 {
425   return gcry_mpi_cmp (b1->r,
426                        b2->r);
427 }
428
429
430 /**
431  * Compare the values of two signatures.
432  *
433  * @param s1 one signature
434  * @param s2 the other signature
435  * @return 0 if the two are equal
436  */
437 int
438 GNUNET_CRYPTO_rsa_signature_cmp (struct GNUNET_CRYPTO_RsaSignature *s1,
439                                  struct GNUNET_CRYPTO_RsaSignature *s2)
440 {
441   char *b1;
442   char *b2;
443   size_t z1;
444   size_t z2;
445   int ret;
446
447   z1 = GNUNET_CRYPTO_rsa_signature_encode (s1,
448                                            &b1);
449   z2 = GNUNET_CRYPTO_rsa_signature_encode (s2,
450                                            &b2);
451   if (z1 != z2)
452     ret = 1;
453   else
454     ret = memcmp (b1,
455                   b2,
456                   z1);
457   GNUNET_free (b1);
458   GNUNET_free (b2);
459   return ret;
460 }
461
462
463 /**
464  * Compare the values of two public keys.
465  *
466  * @param p1 one public key
467  * @param p2 the other public key
468  * @return 0 if the two are equal
469  */
470 int
471 GNUNET_CRYPTO_rsa_public_key_cmp (struct GNUNET_CRYPTO_RsaPublicKey *p1,
472                                   struct GNUNET_CRYPTO_RsaPublicKey *p2)
473 {
474   char *b1;
475   char *b2;
476   size_t z1;
477   size_t z2;
478   int ret;
479
480   z1 = GNUNET_CRYPTO_rsa_public_key_encode (p1,
481                                             &b1);
482   z2 = GNUNET_CRYPTO_rsa_public_key_encode (p2,
483                                             &b2);
484   if (z1 != z2)
485     ret = 1;
486   else
487     ret = memcmp (b1,
488                   b2,
489                   z1);
490   GNUNET_free (b1);
491   GNUNET_free (b2);
492   return ret;
493 }
494
495
496 /**
497  * Compare the values of two private keys.
498  *
499  * @param p1 one private key
500  * @param p2 the other private key
501  * @return 0 if the two are equal
502  */
503 int
504 GNUNET_CRYPTO_rsa_private_key_cmp (struct GNUNET_CRYPTO_RsaPrivateKey *p1,
505                                    struct GNUNET_CRYPTO_RsaPrivateKey *p2)
506 {
507   char *b1;
508   char *b2;
509   size_t z1;
510   size_t z2;
511   int ret;
512
513   z1 = GNUNET_CRYPTO_rsa_private_key_encode (p1,
514                                             &b1);
515   z2 = GNUNET_CRYPTO_rsa_private_key_encode (p2,
516                                             &b2);
517   if (z1 != z2)
518     ret = 1;
519   else
520     ret = memcmp (b1,
521                   b2,
522                   z1);
523   GNUNET_free (b1);
524   GNUNET_free (b2);
525   return ret;
526 }
527
528
529 /**
530  * Obtain the length of the RSA key in bits.
531  *
532  * @param key the public key to introspect
533  * @return length of the key in bits
534  */
535 unsigned int
536 GNUNET_CRYPTO_rsa_public_key_len (const struct GNUNET_CRYPTO_RsaPublicKey *key)
537 {
538   gcry_mpi_t n;
539   int ret;
540   unsigned int rval;
541
542   ret = key_from_sexp (&n, key->sexp, "rsa", "n");
543   if (0 != ret)
544   {
545     /* this is no public RSA key */
546     GNUNET_break (0);
547     return 0;
548   }
549   rval = gcry_mpi_get_nbits (n);
550   gcry_mpi_release (n);
551   return rval;
552 }
553
554
555 /**
556  * Destroy a blinding key
557  *
558  * @param bkey the blinding key to destroy
559  */
560 void
561 GNUNET_CRYPTO_rsa_blinding_key_free (struct GNUNET_CRYPTO_rsa_BlindingKey *bkey)
562 {
563   gcry_mpi_release (bkey->r);
564   GNUNET_free (bkey);
565 }
566
567
568 /**
569  * Print an MPI to a newly created buffer
570  *
571  * @param v MPI to print.
572  * @param[out] buffer set to a buffer with the result
573  * @return number of bytes stored in @a buffer
574  */
575 size_t
576 GNUNET_CRYPTO_mpi_print (gcry_mpi_t v,
577                          char **buffer)
578 {
579   size_t n;
580   char *b;
581   size_t rsize;
582
583   gcry_mpi_print (GCRYMPI_FMT_USG,
584                   NULL,
585                   0,
586                   &n,
587                   v);
588   b = GNUNET_malloc (n);
589   GNUNET_assert (0 ==
590                  gcry_mpi_print (GCRYMPI_FMT_USG,
591                                  (unsigned char *) b,
592                                  n,
593                                  &rsize,
594                                  v));
595   *buffer = b;
596   return n;
597 }
598
599
600 /**
601  * Encode the blinding key in a format suitable for
602  * storing it into a file.
603  *
604  * @param bkey the blinding key
605  * @param[out] buffer set to a buffer with the encoded key
606  * @return size of memory allocated in @a buffer
607  */
608 size_t
609 GNUNET_CRYPTO_rsa_blinding_key_encode (const struct GNUNET_CRYPTO_rsa_BlindingKey *bkey,
610                                        char **buffer)
611 {
612   return GNUNET_CRYPTO_mpi_print (bkey->r, buffer);
613 }
614
615
616 /**
617  * Decode the blinding key from the data-format back
618  * to the "normal", internal format.
619  *
620  * @param buf the buffer where the public key data is stored
621  * @param len the length of the data in @a buf
622  * @return NULL on error
623  */
624 struct GNUNET_CRYPTO_rsa_BlindingKey *
625 GNUNET_CRYPTO_rsa_blinding_key_decode (const char *buf,
626                                        size_t len)
627 {
628   struct GNUNET_CRYPTO_rsa_BlindingKey *bkey;
629   size_t rsize;
630
631   bkey = GNUNET_new (struct GNUNET_CRYPTO_rsa_BlindingKey);
632   if (0 !=
633       gcry_mpi_scan (&bkey->r,
634                      GCRYMPI_FMT_USG,
635                      (const unsigned char *) buf,
636                      len,
637                      &rsize))
638   {
639     GNUNET_break_op (0);
640     GNUNET_free (bkey);
641     return NULL;
642   }
643   return bkey;
644 }
645
646
647 /**
648  * Computes a full domain hash seeded by the given public key.
649  * This gives a measure of provable security to the Taler exchange
650  * against one-more forgery attacks.  See:
651  *   https://eprint.iacr.org/2001/002.pdf
652  *   http://www.di.ens.fr/~pointche/Documents/Papers/2001_fcA.pdf
653  *
654  * @param[out] r MPI value set to the FDH
655  * @param hash initial hash of the message to sign
656  * @param pkey the public key of the signer
657  * @param rsize FIXME JEFF
658  * @return libgcrypt error that to represent an allocation failure
659  */
660 gcry_error_t
661 rsa_full_domain_hash (gcry_mpi_t *r,
662                       const struct GNUNET_HashCode *hash,
663                       const struct GNUNET_CRYPTO_RsaPublicKey *pkey,
664                       size_t *rsize)
665 {
666   unsigned int i;
667   unsigned int nbits;
668   unsigned int nhashes;
669   gcry_error_t rc;
670   char *buf;
671   size_t buf_len;
672   gcry_md_hd_t h;
673   gcry_md_hd_t h0;
674   struct GNUNET_HashCode *hs;
675
676   /* Uncomment the following to debug without using the full domain hash */
677   /*
678   rc = gcry_mpi_scan (r,
679                       GCRYMPI_FMT_USG,
680                       (const unsigned char *)hash,
681                       sizeof(struct GNUNET_HashCode),
682                       rsize);
683   return rc;
684   */
685
686   nbits = GNUNET_CRYPTO_rsa_public_key_len (pkey);
687   if (nbits < 512)
688     nbits = 512;
689
690   /* Already almost an HMAC since we consume a hash, so no GCRY_MD_FLAG_HMAC. */
691   rc = gcry_md_open (&h, GCRY_MD_SHA512, 0);
692   if (0 != rc)
693     return rc;
694
695   // We seed with the public denomination key as a homage to RSA-PSS by
696   // Mihir Bellare and Phillip Rogaway.  Doing this lowers the degree
697   // of the hypothetical polyomial-time attack on RSA-KTI created by a
698   // polynomial-time one-more forgary attack.  Yey seeding!
699   buf_len = GNUNET_CRYPTO_rsa_public_key_encode (pkey, &buf);
700   gcry_md_write (h, buf, buf_len);
701   GNUNET_free (buf);
702
703   nhashes = (nbits-1) / (8 * sizeof(struct GNUNET_HashCode)) + 1;
704   hs = GNUNET_new_array (nhashes,
705                          struct GNUNET_HashCode);
706   for (i=0; i<nhashes; i++)
707   {
708     gcry_md_write (h, hash, sizeof(struct GNUNET_HashCode));
709     rc = gcry_md_copy (&h0, h);
710     if (0 != rc)
711     {
712       gcry_md_close (h0);
713       break;
714     }
715     gcry_md_putc (h0, i % 256);
716     memcpy (&hs[i],
717             gcry_md_read (h0, GCRY_MD_SHA512),
718             sizeof(struct GNUNET_HashCode));
719     gcry_md_close (h0);
720   }
721   gcry_md_close (h);
722   if (0 != rc)
723   {
724     GNUNET_free (hs);
725     return rc;
726   }
727
728   rc = gcry_mpi_scan (r,
729                       GCRYMPI_FMT_USG,
730                       (const unsigned char *) hs,
731                       nhashes * sizeof(struct GNUNET_HashCode),
732                       rsize);
733   GNUNET_free (hs);
734   if (0 != rc)
735     return rc;
736
737   // Do not allow *r to exceed n or signatures fail to verify unpredictably.
738   // This happening with  gcry_mpi_clear_highbit (*r, nbits-1) so maybe
739   // gcry_mpi_clear_highbit is broken, but setting the highbit sounds good.
740   gcry_mpi_set_highbit (*r, nbits-2);
741   return rc;
742 }
743
744
745 /**
746  * Blinds the given message with the given blinding key
747  *
748  * @param hash hash of the message to sign
749  * @param bkey the blinding key
750  * @param pkey the public key of the signer
751  * @param[out] buffer set to a buffer with the blinded message to be signed
752  * @return number of bytes stored in @a buffer
753  */
754 size_t
755 GNUNET_CRYPTO_rsa_blind (const struct GNUNET_HashCode *hash,
756                          struct GNUNET_CRYPTO_rsa_BlindingKey *bkey,
757                          struct GNUNET_CRYPTO_RsaPublicKey *pkey,
758                          char **buffer)
759 {
760   gcry_mpi_t data;
761   gcry_mpi_t ne[2];
762   gcry_mpi_t r_e;
763   gcry_mpi_t data_r_e;
764   size_t rsize;
765   size_t n;
766   gcry_error_t rc;
767   int ret;
768
769   ret = key_from_sexp (ne, pkey->sexp, "public-key", "ne");
770   if (0 != ret)
771     ret = key_from_sexp (ne, pkey->sexp, "rsa", "ne");
772   if (0 != ret)
773   {
774     GNUNET_break (0);
775     *buffer = NULL;
776     return 0;
777   }
778
779   rc = rsa_full_domain_hash (&data, hash, pkey, &rsize);
780   if (0 != rc)  // Allocation error in libgcrypt
781   {
782     GNUNET_break (0);
783     gcry_mpi_release (ne[0]);
784     gcry_mpi_release (ne[1]);
785     *buffer = NULL;
786     return 0;
787   }
788   r_e = gcry_mpi_new (0);
789   gcry_mpi_powm (r_e,
790                  bkey->r,
791                  ne[1],
792                  ne[0]);
793   data_r_e = gcry_mpi_new (0);
794   gcry_mpi_mulm (data_r_e,
795                  data,
796                  r_e,
797                  ne[0]);
798   gcry_mpi_release (data);
799   gcry_mpi_release (ne[0]);
800   gcry_mpi_release (ne[1]);
801   gcry_mpi_release (r_e);
802
803   n = GNUNET_CRYPTO_mpi_print (data_r_e, buffer);
804   gcry_mpi_release (data_r_e);
805   return n;
806 }
807
808
809 /**
810  * Convert an MPI to an S-expression suitable for signature operations.
811  *
812  * @param value pointer to the data to convert
813  * @return converted s-expression
814  */
815 static gcry_sexp_t
816 mpi_to_sexp (gcry_mpi_t value)
817 {
818   gcry_sexp_t data = NULL;
819
820   GNUNET_assert (0 ==
821                  gcry_sexp_build (&data,
822                                   NULL,
823                                   "(data (flags raw) (value %M))",
824                                   value));
825   return data;
826 }
827
828
829 /**
830  * Sign and release the given MPI.
831  *
832  * @param key private key to use for the signing
833  * @param value the MPI to sign
834  * @return NULL on error, signature on success
835  */
836 static struct GNUNET_CRYPTO_RsaSignature *
837 rsa_sign_mpi (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
838               gcry_mpi_t value)
839 {
840   struct GNUNET_CRYPTO_RsaSignature *sig;
841   struct GNUNET_CRYPTO_RsaPublicKey *public_key;
842   gcry_sexp_t data;
843   gcry_sexp_t result;
844
845   data = mpi_to_sexp (value);
846   gcry_mpi_release (value);
847
848   if (0 !=
849       gcry_pk_sign (&result,
850                     data,
851                     key->sexp))
852   {
853     GNUNET_break (0);
854     return NULL;
855   }
856
857   /* verify signature (guards against Lenstra's attack with fault injection...) */
858   public_key = GNUNET_CRYPTO_rsa_private_key_get_public (key);
859   if (0 !=
860       gcry_pk_verify (result,
861                       data,
862                       public_key->sexp))
863   {
864     GNUNET_break (0);
865     GNUNET_CRYPTO_rsa_public_key_free (public_key);
866     gcry_sexp_release (data);
867     gcry_sexp_release (result);
868     return NULL;
869   }
870   GNUNET_CRYPTO_rsa_public_key_free (public_key);
871
872   /* return signature */
873   gcry_sexp_release (data);
874   sig = GNUNET_new (struct GNUNET_CRYPTO_RsaSignature);
875   sig->sexp = result;
876   return sig;
877 }
878
879
880 /**
881  * Sign a blinded value, which must be a full domain hash of a message.
882  *
883  * @param key private key to use for the signing
884  * @param msg the message to sign
885  * @param msg_len number of bytes in @a msg to sign
886  * @return NULL on error, signature on success
887  */
888 struct GNUNET_CRYPTO_RsaSignature *
889 GNUNET_CRYPTO_rsa_sign_blinded (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
890                                 const void *msg,
891                                 size_t msg_len)
892 {
893   gcry_mpi_t v = NULL;
894
895   GNUNET_assert (0 ==
896                  gcry_mpi_scan (&v,
897                                 GCRYMPI_FMT_USG,
898                                 msg,
899                                 msg_len,
900                                 NULL));
901
902   return rsa_sign_mpi (key, v);
903 }
904
905
906 /**
907  * Create and sign a full domain hash of a message.
908  *
909  * @param key private key to use for the signing
910  * @param hash the hash of the message to sign
911  * @return NULL on error, signature on success
912  */
913 struct GNUNET_CRYPTO_RsaSignature *
914 GNUNET_CRYPTO_rsa_sign_fdh (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
915                             const struct GNUNET_HashCode *hash)
916 {
917   struct GNUNET_CRYPTO_RsaPublicKey *pkey;
918   gcry_mpi_t v = NULL;
919   gcry_error_t rc;
920
921   pkey = GNUNET_CRYPTO_rsa_private_key_get_public (key);
922   rc = rsa_full_domain_hash (&v, hash, pkey, NULL);
923   GNUNET_CRYPTO_rsa_public_key_free (pkey);
924   GNUNET_assert (0 == rc);
925
926   return rsa_sign_mpi (key,v);
927 }
928
929
930 /**
931  * Free memory occupied by signature.
932  *
933  * @param sig memory to freee
934  */
935 void
936 GNUNET_CRYPTO_rsa_signature_free (struct GNUNET_CRYPTO_RsaSignature *sig)
937 {
938   gcry_sexp_release (sig->sexp);
939   GNUNET_free (sig);
940 }
941
942
943 /**
944  * Encode the given signature in a format suitable for storing it into a file.
945  *
946  * @param sig the signature
947  * @param[out] buffer set to a buffer with the encoded key
948  * @return size of memory allocated in @a buffer
949  */
950 size_t
951 GNUNET_CRYPTO_rsa_signature_encode (const struct GNUNET_CRYPTO_RsaSignature *sig,
952                                     char **buffer)
953 {
954   size_t n;
955   char *b;
956
957   n = gcry_sexp_sprint (sig->sexp,
958                         GCRYSEXP_FMT_ADVANCED,
959                         NULL,
960                         0);
961   b = GNUNET_malloc (n);
962   GNUNET_assert ((n - 1) ==     /* since the last byte is \0 */
963                  gcry_sexp_sprint (sig->sexp,
964                                    GCRYSEXP_FMT_ADVANCED,
965                                    b,
966                                    n));
967   *buffer = b;
968   return n;
969 }
970
971
972 /**
973  * Decode the signature from the data-format back to the "normal", internal
974  * format.
975  *
976  * @param buf the buffer where the public key data is stored
977  * @param len the length of the data in @a buf
978  * @return NULL on error
979  */
980 struct GNUNET_CRYPTO_RsaSignature *
981 GNUNET_CRYPTO_rsa_signature_decode (const char *buf,
982                                     size_t len)
983 {
984   struct GNUNET_CRYPTO_RsaSignature *sig;
985   int ret;
986   gcry_mpi_t s;
987
988   sig = GNUNET_new (struct GNUNET_CRYPTO_RsaSignature);
989   if (0 !=
990       gcry_sexp_new (&sig->sexp,
991                      buf,
992                      len,
993                      0))
994   {
995     GNUNET_break_op (0);
996     GNUNET_free (sig);
997     return NULL;
998   }
999   /* verify that this is an RSA signature */
1000   ret = key_from_sexp (&s, sig->sexp, "sig-val", "s");
1001   if (0 != ret)
1002     ret = key_from_sexp (&s, sig->sexp, "rsa", "s");
1003   if (0 != ret)
1004   {
1005     /* this is no RSA Signature */
1006     GNUNET_break_op (0);
1007     gcry_sexp_release (sig->sexp);
1008     GNUNET_free (sig);
1009     return NULL;
1010   }
1011   gcry_mpi_release (s);
1012   return sig;
1013 }
1014
1015
1016 /**
1017  * Duplicate the given public key
1018  *
1019  * @param key the public key to duplicate
1020  * @return the duplicate key; NULL upon error
1021  */
1022 struct GNUNET_CRYPTO_RsaPublicKey *
1023 GNUNET_CRYPTO_rsa_public_key_dup (const struct GNUNET_CRYPTO_RsaPublicKey *key)
1024 {
1025   struct GNUNET_CRYPTO_RsaPublicKey *dup;
1026   gcry_sexp_t dup_sexp;
1027   size_t erroff;
1028
1029   /* check if we really are exporting a public key */
1030   dup_sexp = gcry_sexp_find_token (key->sexp, "public-key", 0);
1031   GNUNET_assert (NULL != dup_sexp);
1032   gcry_sexp_release (dup_sexp);
1033   /* copy the sexp */
1034   GNUNET_assert (0 == gcry_sexp_build (&dup_sexp, &erroff, "%S", key->sexp));
1035   dup = GNUNET_new (struct GNUNET_CRYPTO_RsaPublicKey);
1036   dup->sexp = dup_sexp;
1037   return dup;
1038 }
1039
1040
1041 /**
1042  * Unblind a blind-signed signature.  The signature should have been generated
1043  * with #GNUNET_CRYPTO_rsa_sign() using a hash that was blinded with
1044  * #GNUNET_CRYPTO_rsa_blind().
1045  *
1046  * @param sig the signature made on the blinded signature purpose
1047  * @param bkey the blinding key used to blind the signature purpose
1048  * @param pkey the public key of the signer
1049  * @return unblinded signature on success, NULL on error
1050  */
1051 struct GNUNET_CRYPTO_RsaSignature *
1052 GNUNET_CRYPTO_rsa_unblind (struct GNUNET_CRYPTO_RsaSignature *sig,
1053                            struct GNUNET_CRYPTO_rsa_BlindingKey *bkey,
1054                            struct GNUNET_CRYPTO_RsaPublicKey *pkey)
1055 {
1056   gcry_mpi_t n;
1057   gcry_mpi_t s;
1058   gcry_mpi_t r_inv;
1059   gcry_mpi_t ubsig;
1060   int ret;
1061   struct GNUNET_CRYPTO_RsaSignature *sret;
1062
1063   ret = key_from_sexp (&n, pkey->sexp, "public-key", "n");
1064   if (0 != ret)
1065     ret = key_from_sexp (&n, pkey->sexp, "rsa", "n");
1066   if (0 != ret)
1067   {
1068     GNUNET_break_op (0);
1069     return NULL;
1070   }
1071   ret = key_from_sexp (&s, sig->sexp, "sig-val", "s");
1072   if (0 != ret)
1073     ret = key_from_sexp (&s, sig->sexp, "rsa", "s");
1074   if (0 != ret)
1075   {
1076     gcry_mpi_release (n);
1077     GNUNET_break_op (0);
1078     return NULL;
1079   }
1080   r_inv = gcry_mpi_new (0);
1081   if (1 !=
1082       gcry_mpi_invm (r_inv,
1083                      bkey->r,
1084                      n))
1085   {
1086     GNUNET_break_op (0);
1087     gcry_mpi_release (n);
1088     gcry_mpi_release (r_inv);
1089     gcry_mpi_release (s);
1090     return NULL;
1091   }
1092   ubsig = gcry_mpi_new (0);
1093   gcry_mpi_mulm (ubsig, s, r_inv, n);
1094   gcry_mpi_release (n);
1095   gcry_mpi_release (r_inv);
1096   gcry_mpi_release (s);
1097
1098   sret = GNUNET_new (struct GNUNET_CRYPTO_RsaSignature);
1099   GNUNET_assert (0 ==
1100                  gcry_sexp_build (&sret->sexp,
1101                                   NULL,
1102                                   "(sig-val (rsa (s %M)))",
1103                                   ubsig));
1104   gcry_mpi_release (ubsig);
1105   return sret;
1106 }
1107
1108
1109 /**
1110  * Verify whether the given hash corresponds to the given signature and the
1111  * signature is valid with respect to the given public key.
1112  *
1113  * @param hash hash of the message to verify to match the @a sig
1114  * @param sig signature that is being validated
1115  * @param pkey public key of the signer
1116  * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1117  */
1118 int
1119 GNUNET_CRYPTO_rsa_verify (const struct GNUNET_HashCode *hash,
1120                           const struct GNUNET_CRYPTO_RsaSignature *sig,
1121                           const struct GNUNET_CRYPTO_RsaPublicKey *pkey)
1122 {
1123   gcry_sexp_t data;
1124   gcry_mpi_t r;
1125   int rc;
1126
1127   rc = rsa_full_domain_hash (&r, hash, pkey, NULL);
1128   GNUNET_assert (0 == rc);  // Allocation error in libgcrypt
1129   data = mpi_to_sexp(r);
1130   gcry_mpi_release (r);
1131
1132   rc = gcry_pk_verify (sig->sexp,
1133                        data,
1134                        pkey->sexp);
1135   gcry_sexp_release (data);
1136   if (0 != rc)
1137   {
1138     LOG (GNUNET_ERROR_TYPE_WARNING,
1139          _("RSA signature verification failed at %s:%d: %s\n"),
1140          __FILE__,
1141          __LINE__,
1142          gcry_strerror (rc));
1143     return GNUNET_SYSERR;
1144   }
1145   return GNUNET_OK;
1146 }
1147
1148
1149 /**
1150  * Duplicate the given private key
1151  *
1152  * @param key the private key to duplicate
1153  * @return the duplicate key; NULL upon error
1154  */
1155 struct GNUNET_CRYPTO_RsaPrivateKey *
1156 GNUNET_CRYPTO_rsa_private_key_dup (const struct GNUNET_CRYPTO_RsaPrivateKey *key)
1157 {
1158   struct GNUNET_CRYPTO_RsaPrivateKey *dup;
1159   gcry_sexp_t dup_sexp;
1160   size_t erroff;
1161
1162   /* check if we really are exporting a private key */
1163   dup_sexp = gcry_sexp_find_token (key->sexp, "private-key", 0);
1164   GNUNET_assert (NULL != dup_sexp);
1165   gcry_sexp_release (dup_sexp);
1166   /* copy the sexp */
1167   GNUNET_assert (0 == gcry_sexp_build (&dup_sexp, &erroff, "%S", key->sexp));
1168   dup = GNUNET_new (struct GNUNET_CRYPTO_RsaPrivateKey);
1169   dup->sexp = dup_sexp;
1170   return dup;
1171 }
1172
1173
1174 /**
1175  * Duplicate the given private key
1176  *
1177  * @param key the private key to duplicate
1178  * @return the duplicate key; NULL upon error
1179  */
1180 struct GNUNET_CRYPTO_RsaSignature *
1181 GNUNET_CRYPTO_rsa_signature_dup (const struct GNUNET_CRYPTO_RsaSignature *sig)
1182 {
1183   struct GNUNET_CRYPTO_RsaSignature *dup;
1184   gcry_sexp_t dup_sexp;
1185   size_t erroff;
1186   gcry_mpi_t s;
1187   int ret;
1188
1189   /* verify that this is an RSA signature */
1190   ret = key_from_sexp (&s, sig->sexp, "sig-val", "s");
1191   if (0 != ret)
1192     ret = key_from_sexp (&s, sig->sexp, "rsa", "s");
1193   GNUNET_assert (0 == ret);
1194   gcry_mpi_release (s);
1195   /* copy the sexp */
1196   GNUNET_assert (0 == gcry_sexp_build (&dup_sexp, &erroff, "%S", sig->sexp));
1197   dup = GNUNET_new (struct GNUNET_CRYPTO_RsaSignature);
1198   dup->sexp = dup_sexp;
1199   return dup;
1200 }
1201
1202
1203 /* end of util/rsa.c */