2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file util/crypto_rsa.c
23 * @brief public key cryptography (RSA) with libgcrypt
24 * @author Christian Grothoff
26 * Note that the code locks often needlessly on the gcrypt-locking api.
27 * One would think that simple MPI operations should not require locking
28 * (since only global operations on the random pool must be locked,
29 * strictly speaking). But libgcrypt does sometimes require locking in
30 * unexpected places, so the safe solution is to always lock even if it
31 * is not required. The performance impact is minimal anyway.
36 #include "gnunet_common.h"
37 #include "gnunet_crypto_lib.h"
38 #include "gnunet_disk_lib.h"
41 * The private information of an RSA key pair.
42 * NOTE: this must match the definition in crypto_ksk.c
44 struct GNUNET_CRYPTO_RsaPrivateKey
51 * GNUnet mandates a certain format for the encoding
52 * of private RSA key information that is provided
53 * by the RSA implementations. This format is used
54 * to serialize a private RSA key (typically when
55 * writing it to disk).
57 struct RsaPrivateKeyBinaryEncoded
60 * Total size of the structure, in bytes, in big-endian!
62 uint16_t len GNUNET_PACKED;
63 uint16_t sizen GNUNET_PACKED; /* in big-endian! */
64 uint16_t sizee GNUNET_PACKED; /* in big-endian! */
65 uint16_t sized GNUNET_PACKED; /* in big-endian! */
66 uint16_t sizep GNUNET_PACKED; /* in big-endian! */
67 uint16_t sizeq GNUNET_PACKED; /* in big-endian! */
68 uint16_t sizedmp1 GNUNET_PACKED; /* in big-endian! */
69 uint16_t sizedmq1 GNUNET_PACKED; /* in big-endian! */
70 /* followed by the actual values */
74 #define HOSTKEY_LEN 2048
76 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
80 * Log an error message at log-level 'level' that indicates
81 * a failure of the command 'cmd' with the message given
82 * by gcry_strerror(rc).
84 #define LOG_GCRY(level, cmd, rc) do { GNUNET_log(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0);
87 * If target != size, move target bytes to the
88 * end of the size-sized buffer and zero out the
89 * first target-size bytes.
92 adjust (unsigned char *buf, size_t size, size_t target)
96 memmove (&buf[target - size], buf, size);
97 memset (buf, 0, target - size);
102 * This HostKey implementation uses RSA.
104 struct GNUNET_CRYPTO_RsaPrivateKey *
105 GNUNET_CRYPTO_rsa_key_create ()
107 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
109 gcry_sexp_t s_keyparam;
112 gcry_sexp_build (&s_keyparam, NULL,
113 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
115 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
116 gcry_sexp_release (s_keyparam);
118 GNUNET_assert (0 == gcry_pk_testkey (s_key));
120 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
126 * Free memory occupied by hostkey
129 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
131 gcry_sexp_release (hostkey->sexp);
132 GNUNET_free (hostkey);
136 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
139 gcry_sexp_t list, l2;
143 list = gcry_sexp_find_token (sexp, topname, 0);
148 l2 = gcry_sexp_cadr (list);
149 gcry_sexp_release (list);
157 for (s = elems; *s; s++, idx++)
159 l2 = gcry_sexp_find_token (list, s, 1);
162 for (i = 0; i < idx; i++)
164 gcry_free (array[i]);
167 gcry_sexp_release (list);
168 return 3; /* required parameter not found */
170 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
171 gcry_sexp_release (l2);
174 for (i = 0; i < idx; i++)
176 gcry_free (array[i]);
179 gcry_sexp_release (list);
180 return 4; /* required parameter is invalid */
183 gcry_sexp_release (list);
188 * Extract the public key of the host.
189 * @param priv the private key
190 * @param pub where to write the public key
193 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
195 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
202 rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
204 rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
206 rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
207 GNUNET_assert (0 == rc);
209 htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
210 sizeof (pub->padding));
211 pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
213 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
215 gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
217 adjust (&pub->key[0], size, GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
218 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
220 gcry_mpi_print (GCRYMPI_FMT_USG,
222 [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
224 adjust (&pub->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
225 GNUNET_CRYPTO_RSA_KEY_LENGTH -
226 GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
227 gcry_mpi_release (skey[0]);
228 gcry_mpi_release (skey[1]);
233 * Internal: publicKey => RSA-Key.
235 * Note that the return type is not actually a private
236 * key but rather an sexpression for the public key!
238 static struct GNUNET_CRYPTO_RsaPrivateKey *
239 public2PrivateKey (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
242 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
250 if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
251 (ntohs (publicKey->len) !=
252 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
253 sizeof (publicKey->padding)))
258 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
259 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
262 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
265 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
266 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
267 &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
271 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
272 gcry_mpi_release (n);
275 rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
277 gcry_mpi_release (n);
278 gcry_mpi_release (e);
281 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
284 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
291 * Encode the private key in a format suitable for
292 * storing it into a file.
293 * @returns encoding of the private key.
294 * The first 4 bytes give the size of the array, as usual.
296 static struct RsaPrivateKeyBinaryEncoded *
297 rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
299 struct RsaPrivateKeyBinaryEncoded *retval;
308 if (gcry_pk_testkey (hostkey->sexp))
315 memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
316 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
318 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
320 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
322 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
324 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
326 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
327 GNUNET_assert (0 == rc);
328 size = sizeof (struct RsaPrivateKeyBinaryEncoded);
329 for (i = 0; i < 6; i++)
334 gcry_mpi_aprint (GCRYMPI_FMT_USG,
335 (unsigned char **) &pbu[i], &sizes[i],
345 GNUNET_assert (size < 65536);
346 retval = GNUNET_malloc (size);
347 retval->len = htons (size);
349 retval->sizen = htons (sizes[0]);
350 memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
352 retval->sizee = htons (sizes[1]);
353 memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
355 retval->sized = htons (sizes[2]);
356 memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
359 retval->sizep = htons (sizes[4]);
360 memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
362 retval->sizeq = htons (sizes[3]);
363 memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
365 retval->sizedmp1 = htons (0);
366 retval->sizedmq1 = htons (0);
367 memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
368 for (i = 0; i < 6; i++)
371 gcry_mpi_release (pkv[i]);
379 * Decode the private key from the file-format back
380 * to the "normal", internal format.
382 * @param buf the buffer where the private key data is stored
383 * @param len the length of the data in 'buffer'
385 struct GNUNET_CRYPTO_RsaPrivateKey *
386 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
388 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
389 const struct RsaPrivateKeyBinaryEncoded *encoding =
390 (const struct RsaPrivateKeyBinaryEncoded *) buf;
392 gcry_mpi_t n, e, d, p, q, u;
398 enc_len = ntohs (encoding->len);
403 size = ntohs (encoding->sizen);
404 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
405 &((const unsigned char *) (&encoding[1]))[pos], size,
407 pos += ntohs (encoding->sizen);
410 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
413 size = ntohs (encoding->sizee);
414 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
415 &((const unsigned char *) (&encoding[1]))[pos], size,
417 pos += ntohs (encoding->sizee);
420 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
421 gcry_mpi_release (n);
424 size = ntohs (encoding->sized);
425 rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
426 &((const unsigned char *) (&encoding[1]))[pos], size,
428 pos += ntohs (encoding->sized);
431 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
432 gcry_mpi_release (n);
433 gcry_mpi_release (e);
437 size = ntohs (encoding->sizep);
440 rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
441 &((const unsigned char *) (&encoding[1]))[pos], size,
443 pos += ntohs (encoding->sizep);
446 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
447 gcry_mpi_release (n);
448 gcry_mpi_release (e);
449 gcry_mpi_release (d);
455 size = ntohs (encoding->sizeq);
458 rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
459 &((const unsigned char *) (&encoding[1]))[pos], size,
461 pos += ntohs (encoding->sizeq);
464 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
465 gcry_mpi_release (n);
466 gcry_mpi_release (e);
467 gcry_mpi_release (d);
469 gcry_mpi_release (q);
475 pos += ntohs (encoding->sizedmp1);
476 pos += ntohs (encoding->sizedmq1);
478 ntohs (encoding->len) - sizeof (struct RsaPrivateKeyBinaryEncoded) - pos;
481 rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
482 &((const unsigned char *) (&encoding[1]))[pos], size,
486 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
487 gcry_mpi_release (n);
488 gcry_mpi_release (e);
489 gcry_mpi_release (d);
491 gcry_mpi_release (p);
493 gcry_mpi_release (q);
500 if ((p != NULL) && (q != NULL) && (u != NULL))
502 rc = gcry_sexp_build (&res, &size, /* erroff */
503 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
508 if ((p != NULL) && (q != NULL))
510 rc = gcry_sexp_build (&res, &size, /* erroff */
511 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
516 rc = gcry_sexp_build (&res, &size, /* erroff */
517 "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
520 gcry_mpi_release (n);
521 gcry_mpi_release (e);
522 gcry_mpi_release (d);
524 gcry_mpi_release (p);
526 gcry_mpi_release (q);
528 gcry_mpi_release (u);
531 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
533 if (gcry_pk_testkey (res))
535 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
539 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
546 * Create a new private key by reading it from a file. If the
547 * files does not exist, create a new key and write it to the
548 * file. Caller must free return value. Note that this function
549 * can not guarantee that another process might not be trying
550 * the same operation on the same file at the same time.
551 * If the contents of the file
552 * are invalid the old file is deleted and a fresh key is
555 * @return new private key, NULL on error (for example,
558 struct GNUNET_CRYPTO_RsaPrivateKey *
559 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
561 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
562 struct RsaPrivateKeyBinaryEncoded *enc;
564 struct GNUNET_DISK_FileHandle *fd;
568 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
569 struct GNUNET_PeerIdentity pid;
571 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
573 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
575 fd = GNUNET_DISK_file_open (filename,
576 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
577 | GNUNET_DISK_OPEN_FAILIFEXISTS,
578 GNUNET_DISK_PERM_USER_READ |
579 GNUNET_DISK_PERM_USER_WRITE);
584 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
586 /* must exist but not be accessible, fail for good! */
587 if (0 != ACCESS (filename, R_OK))
588 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access",
591 GNUNET_break (0); /* what is going on!? */
596 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", filename);
602 GNUNET_DISK_file_lock (fd, 0,
603 sizeof (struct RsaPrivateKeyBinaryEncoded),
610 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
611 _("Could not aquire lock on file `%s': %s...\n"), filename,
615 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
616 _("Creating a new private key. This may take a while.\n"));
617 ret = GNUNET_CRYPTO_rsa_key_create ();
618 GNUNET_assert (ret != NULL);
619 enc = rsa_encode_key (ret);
620 GNUNET_assert (enc != NULL);
621 GNUNET_assert (ntohs (enc->len) ==
622 GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
625 GNUNET_DISK_file_sync (fd);
627 GNUNET_DISK_file_unlock (fd, 0,
628 sizeof (struct RsaPrivateKeyBinaryEncoded)))
629 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
630 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
631 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
632 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
633 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
634 _("I am host `%s'. Stored new private key in `%s'.\n"),
635 GNUNET_i2s (&pid), filename);
638 /* hostkey file exists already, read it! */
639 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
640 GNUNET_DISK_PERM_NONE);
643 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", filename);
650 GNUNET_DISK_file_lock (fd, 0,
651 sizeof (struct RsaPrivateKeyBinaryEncoded),
657 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
658 _("Could not aquire lock on file `%s': %s...\n"), filename,
660 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
662 ("This may be ok if someone is currently generating a hostkey.\n"));
667 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
669 /* eh, what!? File we opened is now gone!? */
670 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
672 GNUNET_DISK_file_unlock (fd, 0,
673 sizeof (struct RsaPrivateKeyBinaryEncoded)))
674 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
675 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
679 if (GNUNET_YES != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES))
681 if (fs < sizeof (struct RsaPrivateKeyBinaryEncoded))
683 /* maybe we got the read lock before the hostkey generating
684 * process had a chance to get the write lock; give it up! */
686 GNUNET_DISK_file_unlock (fd, 0,
687 sizeof (struct RsaPrivateKeyBinaryEncoded)))
688 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
691 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
693 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
694 filename, (unsigned int) fs,
695 (unsigned int) sizeof (struct RsaPrivateKeyBinaryEncoded));
696 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
698 ("This may be ok if someone is currently generating a hostkey.\n"));
700 sleep (2); /* wait a bit longer! */
705 enc = GNUNET_malloc (fs);
706 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
707 len = ntohs (enc->len);
710 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
712 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
714 ("File `%s' does not contain a valid private key. Deleting it.\n"),
716 if (0 != UNLINK (filename))
718 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
723 GNUNET_DISK_file_unlock (fd, 0,
724 sizeof (struct RsaPrivateKeyBinaryEncoded)))
725 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
726 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
729 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
730 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
731 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
732 _("I am host `%s'. Read private key from `%s'.\n"),
733 GNUNET_i2s (&pid), filename);
740 * Encrypt a block with the public key of another host that uses the
743 * @param block the block to encrypt
744 * @param size the size of block
745 * @param publicKey the encoded public key used to encrypt
746 * @param target where to store the encrypted block
747 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
750 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
751 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
753 struct GNUNET_CRYPTO_RsaEncryptedData *target)
757 struct GNUNET_CRYPTO_RsaPrivateKey *pubkey;
763 GNUNET_assert (size <= sizeof (GNUNET_HashCode));
764 pubkey = public2PrivateKey (publicKey);
766 return GNUNET_SYSERR;
769 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
771 gcry_sexp_build (&data, &erroff,
772 "(data (flags pkcs1)(value %m))", val));
773 gcry_mpi_release (val);
774 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, pubkey->sexp));
775 gcry_sexp_release (data);
776 GNUNET_CRYPTO_rsa_key_free (pubkey);
778 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
779 gcry_sexp_release (result);
780 isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
782 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
783 isize, &isize, rval));
784 gcry_mpi_release (rval);
785 adjust (&target->encoding[0], isize,
786 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
791 * Decrypt a given block with the hostkey.
793 * @param key the key with which to decrypt this block
794 * @param block the data to decrypt, encoded as returned by encrypt
795 * @param result pointer to a location where the result can be stored
796 * @param max the maximum number of bits to store for the result, if
797 * the decrypted block is bigger, an error is returned
798 * @return the size of the decrypted block, -1 on error
801 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
802 const struct GNUNET_CRYPTO_RsaEncryptedData * block,
803 void *result, size_t max)
805 gcry_sexp_t resultsexp;
814 GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
816 size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
818 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
821 gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
823 gcry_mpi_release (val);
824 GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
825 gcry_sexp_release (data);
826 /* resultsexp has format "(value %m)" */
827 GNUNET_assert (NULL !=
828 (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
829 gcry_sexp_release (resultsexp);
830 tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
831 size = max + HOSTKEY_LEN / 8;
832 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
833 gcry_mpi_release (val);
835 endp += (size - max);
837 memcpy (result, endp, size);
844 * Sign a given block.
846 * @param key private key to use for the signing
847 * @param purpose what to sign (size, purpose)
848 * @param sig where to write the signature
849 * @return GNUNET_SYSERR on error, GNUNET_OK on success
852 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
853 const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
854 struct GNUNET_CRYPTO_RsaSignature *sig)
864 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
865 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
866 bufSize = strlen (FORMATSTRING) + 1;
867 buff = GNUNET_malloc (bufSize);
868 memcpy (buff, FORMATSTRING, bufSize);
872 ("0123456789012345678901234567890123456789012345678901234567890123))")
873 - 1], &hc, sizeof (GNUNET_HashCode));
874 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
876 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
877 gcry_sexp_release (data);
878 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
879 gcry_sexp_release (result);
880 ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
882 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
884 gcry_mpi_release (rval);
885 adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
893 * @param purpose what is the purpose that the signature should have?
894 * @param validate block to validate (size, purpose, data)
895 * @param sig signature that is being validated
896 * @param publicKey public key of the signer
897 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
900 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
901 const struct GNUNET_CRYPTO_RsaSignaturePurpose
903 const struct GNUNET_CRYPTO_RsaSignature *sig,
904 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
911 struct GNUNET_CRYPTO_RsaPrivateKey *hostkey;
918 if (purpose != ntohl (validate->purpose))
919 return GNUNET_SYSERR; /* purpose mismatch */
920 GNUNET_CRYPTO_hash (validate, ntohl (validate->size), &hc);
921 size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
923 gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
924 (const unsigned char *) sig, size, &size));
926 gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
928 gcry_mpi_release (val);
929 bufSize = strlen (FORMATSTRING) + 1;
930 buff = GNUNET_malloc (bufSize);
931 memcpy (buff, FORMATSTRING, bufSize);
933 [strlen (FORMATSTRING) -
935 ("0123456789012345678901234567890123456789012345678901234567890123))")],
936 &hc, sizeof (GNUNET_HashCode));
937 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
939 hostkey = public2PrivateKey (publicKey);
942 gcry_sexp_release (data);
943 gcry_sexp_release (sigdata);
944 return GNUNET_SYSERR;
946 rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
947 GNUNET_CRYPTO_rsa_key_free (hostkey);
948 gcry_sexp_release (data);
949 gcry_sexp_release (sigdata);
952 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
953 _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
954 __LINE__, gcry_strerror (rc));
955 return GNUNET_SYSERR;
961 /* end of crypto_rsa.c */