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"
39 #include "gnunet_strings_lib.h"
41 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
43 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
45 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
48 * The private information of an RSA key pair.
49 * NOTE: this must match the definition in crypto_ksk.c
51 struct GNUNET_CRYPTO_RsaPrivateKey
57 #define HOSTKEY_LEN 2048
59 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
63 * Log an error message at log-level 'level' that indicates
64 * a failure of the command 'cmd' with the message given
65 * by gcry_strerror(rc).
67 #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);
70 * If target != size, move target bytes to the
71 * end of the size-sized buffer and zero out the
72 * first target-size bytes.
75 adjust (unsigned char *buf, size_t size, size_t target)
79 memmove (&buf[target - size], buf, size);
80 memset (buf, 0, target - size);
85 * Create a new private key. Caller must free return value.
87 * @return fresh private key
89 struct GNUNET_CRYPTO_RsaPrivateKey *
90 GNUNET_CRYPTO_rsa_key_create ()
92 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
94 gcry_sexp_t s_keyparam;
97 gcry_sexp_build (&s_keyparam, NULL,
98 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
100 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
101 gcry_sexp_release (s_keyparam);
103 GNUNET_assert (0 == gcry_pk_testkey (s_key));
105 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
111 * Free memory occupied by hostkey
112 * @param hostkey pointer to the memory to free
115 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
117 gcry_sexp_release (hostkey->sexp);
118 GNUNET_free (hostkey);
122 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
125 gcry_sexp_t list, l2;
129 list = gcry_sexp_find_token (sexp, topname, 0);
134 l2 = gcry_sexp_cadr (list);
135 gcry_sexp_release (list);
143 for (s = elems; *s; s++, idx++)
145 l2 = gcry_sexp_find_token (list, s, 1);
148 for (i = 0; i < idx; i++)
150 gcry_free (array[i]);
153 gcry_sexp_release (list);
154 return 3; /* required parameter not found */
156 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
157 gcry_sexp_release (l2);
160 for (i = 0; i < idx; i++)
162 gcry_free (array[i]);
165 gcry_sexp_release (list);
166 return 4; /* required parameter is invalid */
169 gcry_sexp_release (list);
174 * Extract the public key of the host.
175 * @param priv the private key
176 * @param pub where to write the public key
179 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
181 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
188 rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
190 rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
192 rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
193 GNUNET_assert (0 == rc);
195 htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
196 sizeof (pub->padding));
197 pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
199 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
201 gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
203 adjust (&pub->key[0], size, GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
204 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
206 gcry_mpi_print (GCRYMPI_FMT_USG,
208 [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
210 adjust (&pub->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
211 GNUNET_CRYPTO_RSA_KEY_LENGTH -
212 GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
213 gcry_mpi_release (skey[0]);
214 gcry_mpi_release (skey[1]);
219 * Convert a public key to a string.
221 * @param pub key to convert
222 * @return string representing 'pub'
225 GNUNET_CRYPTO_rsa_public_key_to_string (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
228 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
232 keylen += 5 - keylen % 5;
234 pubkeybuf = GNUNET_malloc (keylen + 1);
235 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
236 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
241 GNUNET_free (pubkeybuf);
250 * Convert a string representing a public key to a public key.
252 * @param enc encoded public key
253 * @param enclen number of bytes in enc (without 0-terminator)
254 * @param pub where to store the public key
255 * @return GNUNET_OK on success
258 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc,
260 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
262 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
265 keylen += 5 - keylen % 5;
267 if (enclen != keylen)
268 return GNUNET_SYSERR;
270 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
271 (unsigned char*) pub,
272 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
273 return GNUNET_SYSERR;
274 if ( (ntohs (pub->len) != sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) ||
275 (ntohs (pub->padding) != 0) ||
276 (ntohs (pub->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) )
277 return GNUNET_SYSERR;
283 * Internal: publicKey => RSA-Key.
285 * Note that the return type is not actually a private
286 * key but rather an sexpression for the public key!
288 static struct GNUNET_CRYPTO_RsaPrivateKey *
289 public2PrivateKey (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
292 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
300 if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
301 (ntohs (publicKey->len) !=
302 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
303 sizeof (publicKey->padding)))
308 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
309 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
312 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
315 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
316 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
317 &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
321 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
322 gcry_mpi_release (n);
325 rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
327 gcry_mpi_release (n);
328 gcry_mpi_release (e);
331 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
334 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
341 * Encode the private key in a format suitable for
342 * storing it into a file.
343 * @returns encoding of the private key.
344 * The first 4 bytes give the size of the array, as usual.
346 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
347 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
349 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *retval;
358 if (gcry_pk_testkey (hostkey->sexp))
365 memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
366 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
368 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
370 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
372 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
374 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
376 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
377 GNUNET_assert (0 == rc);
378 size = sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded);
379 for (i = 0; i < 6; i++)
384 gcry_mpi_aprint (GCRYMPI_FMT_USG,
385 (unsigned char **) &pbu[i], &sizes[i],
395 GNUNET_assert (size < 65536);
396 retval = GNUNET_malloc (size);
397 retval->len = htons (size);
399 retval->sizen = htons (sizes[0]);
400 memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
402 retval->sizee = htons (sizes[1]);
403 memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
405 retval->sized = htons (sizes[2]);
406 memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
409 retval->sizep = htons (sizes[4]);
410 memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
412 retval->sizeq = htons (sizes[3]);
413 memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
415 retval->sizedmp1 = htons (0);
416 retval->sizedmq1 = htons (0);
417 memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
418 for (i = 0; i < 6; i++)
421 gcry_mpi_release (pkv[i]);
430 * Decode the private key from the file-format back
431 * to the "normal", internal format.
433 * @param buf the buffer where the private key data is stored
434 * @param len the length of the data in 'buffer'
436 struct GNUNET_CRYPTO_RsaPrivateKey *
437 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
439 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
440 const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *encoding =
441 (const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *) buf;
443 gcry_mpi_t n, e, d, p, q, u;
449 enc_len = ntohs (encoding->len);
454 size = ntohs (encoding->sizen);
455 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
456 &((const unsigned char *) (&encoding[1]))[pos], size,
458 pos += ntohs (encoding->sizen);
461 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
464 size = ntohs (encoding->sizee);
465 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
466 &((const unsigned char *) (&encoding[1]))[pos], size,
468 pos += ntohs (encoding->sizee);
471 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
472 gcry_mpi_release (n);
475 size = ntohs (encoding->sized);
476 rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
477 &((const unsigned char *) (&encoding[1]))[pos], size,
479 pos += ntohs (encoding->sized);
482 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
483 gcry_mpi_release (n);
484 gcry_mpi_release (e);
488 size = ntohs (encoding->sizep);
491 rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
492 &((const unsigned char *) (&encoding[1]))[pos], size,
494 pos += ntohs (encoding->sizep);
497 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
498 gcry_mpi_release (n);
499 gcry_mpi_release (e);
500 gcry_mpi_release (d);
506 size = ntohs (encoding->sizeq);
509 rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
510 &((const unsigned char *) (&encoding[1]))[pos], size,
512 pos += ntohs (encoding->sizeq);
515 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
516 gcry_mpi_release (n);
517 gcry_mpi_release (e);
518 gcry_mpi_release (d);
520 gcry_mpi_release (q);
526 pos += ntohs (encoding->sizedmp1);
527 pos += ntohs (encoding->sizedmq1);
529 ntohs (encoding->len) - sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded) - pos;
532 rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
533 &((const unsigned char *) (&encoding[1]))[pos], size,
537 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
538 gcry_mpi_release (n);
539 gcry_mpi_release (e);
540 gcry_mpi_release (d);
542 gcry_mpi_release (p);
544 gcry_mpi_release (q);
551 if ((p != NULL) && (q != NULL) && (u != NULL))
553 rc = gcry_sexp_build (&res, &size, /* erroff */
554 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
559 if ((p != NULL) && (q != NULL))
561 rc = gcry_sexp_build (&res, &size, /* erroff */
562 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
567 rc = gcry_sexp_build (&res, &size, /* erroff */
568 "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
571 gcry_mpi_release (n);
572 gcry_mpi_release (e);
573 gcry_mpi_release (d);
575 gcry_mpi_release (p);
577 gcry_mpi_release (q);
579 gcry_mpi_release (u);
582 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
584 if (gcry_pk_testkey (res))
586 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
590 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
597 * Create a new private key by reading it from a file. If the
598 * files does not exist, create a new key and write it to the
599 * file. Caller must free return value. Note that this function
600 * can not guarantee that another process might not be trying
601 * the same operation on the same file at the same time.
602 * If the contents of the file
603 * are invalid the old file is deleted and a fresh key is
606 * @return new private key, NULL on error (for example,
609 struct GNUNET_CRYPTO_RsaPrivateKey *
610 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
612 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
613 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
615 struct GNUNET_DISK_FileHandle *fd;
619 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
620 struct GNUNET_PeerIdentity pid;
622 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
624 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
626 fd = GNUNET_DISK_file_open (filename,
627 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
628 | GNUNET_DISK_OPEN_FAILIFEXISTS,
629 GNUNET_DISK_PERM_USER_READ |
630 GNUNET_DISK_PERM_USER_WRITE);
635 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
637 /* must exist but not be accessible, fail for good! */
638 if (0 != ACCESS (filename, R_OK))
639 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
641 GNUNET_break (0); /* what is going on!? */
646 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
652 GNUNET_DISK_file_lock (fd, 0,
653 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
660 LOG (GNUNET_ERROR_TYPE_ERROR,
661 _("Could not aquire lock on file `%s': %s...\n"), filename,
665 LOG (GNUNET_ERROR_TYPE_INFO,
666 _("Creating a new private key. This may take a while.\n"));
667 ret = GNUNET_CRYPTO_rsa_key_create ();
668 GNUNET_assert (ret != NULL);
669 enc = GNUNET_CRYPTO_rsa_encode_key (ret);
670 GNUNET_assert (enc != NULL);
671 GNUNET_assert (ntohs (enc->len) ==
672 GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
675 GNUNET_DISK_file_sync (fd);
677 GNUNET_DISK_file_unlock (fd, 0,
678 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
679 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
680 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
681 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
682 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
683 LOG (GNUNET_ERROR_TYPE_INFO,
684 _("I am host `%s'. Stored new private key in `%s'.\n"),
685 GNUNET_i2s (&pid), filename);
688 /* hostkey file exists already, read it! */
689 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
690 GNUNET_DISK_PERM_NONE);
693 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
700 GNUNET_DISK_file_lock (fd, 0,
701 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
707 LOG (GNUNET_ERROR_TYPE_ERROR,
708 _("Could not aquire lock on file `%s': %s...\n"), filename,
710 LOG (GNUNET_ERROR_TYPE_ERROR,
712 ("This may be ok if someone is currently generating a hostkey.\n"));
717 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
719 /* eh, what!? File we opened is now gone!? */
720 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
722 GNUNET_DISK_file_unlock (fd, 0,
723 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
724 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
725 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
729 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
731 if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
733 /* maybe we got the read lock before the hostkey generating
734 * process had a chance to get the write lock; give it up! */
736 GNUNET_DISK_file_unlock (fd, 0,
737 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
738 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
741 LOG (GNUNET_ERROR_TYPE_ERROR,
743 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
744 filename, (unsigned int) fs,
745 (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
746 LOG (GNUNET_ERROR_TYPE_ERROR,
748 ("This may be ok if someone is currently generating a hostkey.\n"));
750 sleep (2); /* wait a bit longer! */
755 enc = GNUNET_malloc (fs);
756 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
757 len = ntohs (enc->len);
760 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
762 LOG (GNUNET_ERROR_TYPE_ERROR,
763 _("File `%s' does not contain a valid private key. Deleting it.\n"),
765 if (0 != UNLINK (filename))
767 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
772 GNUNET_DISK_file_unlock (fd, 0,
773 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
774 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
775 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
778 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
779 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
780 LOG (GNUNET_ERROR_TYPE_INFO,
781 _("I am host `%s'. Read private key from `%s'.\n"), GNUNET_i2s (&pid),
789 * Setup a hostkey file for a peer given the name of the
790 * configuration file (!). This function is used so that
791 * at a later point code can be certain that reading a
792 * hostkey is fast (for example in time-dependent testcases).
794 * @param cfg_name name of the configuration file to use
797 GNUNET_CRYPTO_setup_hostkey (const char *cfg_name)
799 struct GNUNET_CONFIGURATION_Handle *cfg;
800 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
803 cfg = GNUNET_CONFIGURATION_create ();
804 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
806 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
808 pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
810 GNUNET_CRYPTO_rsa_key_free (pk);
813 GNUNET_CONFIGURATION_destroy (cfg);
818 * Encrypt a block with the public key of another host that uses the
821 * @param block the block to encrypt
822 * @param size the size of block
823 * @param publicKey the encoded public key used to encrypt
824 * @param target where to store the encrypted block
825 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
828 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
829 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
831 struct GNUNET_CRYPTO_RsaEncryptedData *target)
835 struct GNUNET_CRYPTO_RsaPrivateKey *pubkey;
841 GNUNET_assert (size <= sizeof (GNUNET_HashCode));
842 pubkey = public2PrivateKey (publicKey);
844 return GNUNET_SYSERR;
847 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
849 gcry_sexp_build (&data, &erroff,
850 "(data (flags pkcs1)(value %m))", val));
851 gcry_mpi_release (val);
852 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, pubkey->sexp));
853 gcry_sexp_release (data);
854 GNUNET_CRYPTO_rsa_key_free (pubkey);
856 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
857 gcry_sexp_release (result);
858 isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
860 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
861 isize, &isize, rval));
862 gcry_mpi_release (rval);
863 adjust (&target->encoding[0], isize,
864 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
870 * Decrypt a given block with the hostkey.
872 * @param key the key with which to decrypt this block
873 * @param block the data to decrypt, encoded as returned by encrypt
874 * @param result pointer to a location where the result can be stored
875 * @param max the maximum number of bits to store for the result, if
876 * the decrypted block is bigger, an error is returned
877 * @return the size of the decrypted block, -1 on error
880 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
881 const struct GNUNET_CRYPTO_RsaEncryptedData * block,
882 void *result, size_t max)
884 gcry_sexp_t resultsexp;
893 GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
895 size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
897 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
900 gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
902 gcry_mpi_release (val);
903 GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
904 gcry_sexp_release (data);
905 /* resultsexp has format "(value %m)" */
906 GNUNET_assert (NULL !=
907 (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
908 gcry_sexp_release (resultsexp);
909 tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
910 size = max + HOSTKEY_LEN / 8;
911 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
912 gcry_mpi_release (val);
914 endp += (size - max);
916 memcpy (result, endp, size);
923 * Sign a given block.
925 * @param key private key to use for the signing
926 * @param purpose what to sign (size, purpose)
927 * @param sig where to write the signature
928 * @return GNUNET_SYSERR on error, GNUNET_OK on success
931 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
932 const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
933 struct GNUNET_CRYPTO_RsaSignature *sig)
943 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
944 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
945 bufSize = strlen (FORMATSTRING) + 1;
946 buff = GNUNET_malloc (bufSize);
947 memcpy (buff, FORMATSTRING, bufSize);
951 ("0123456789012345678901234567890123456789012345678901234567890123))")
952 - 1], &hc, sizeof (GNUNET_HashCode));
953 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
955 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
956 gcry_sexp_release (data);
957 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
958 gcry_sexp_release (result);
959 ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
961 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
963 gcry_mpi_release (rval);
964 adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
972 * @param purpose what is the purpose that the signature should have?
973 * @param validate block to validate (size, purpose, data)
974 * @param sig signature that is being validated
975 * @param publicKey public key of the signer
976 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
979 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
980 const struct GNUNET_CRYPTO_RsaSignaturePurpose
982 const struct GNUNET_CRYPTO_RsaSignature *sig,
983 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
990 struct GNUNET_CRYPTO_RsaPrivateKey *hostkey;
997 if (purpose != ntohl (validate->purpose))
998 return GNUNET_SYSERR; /* purpose mismatch */
999 GNUNET_CRYPTO_hash (validate, ntohl (validate->size), &hc);
1000 size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1002 gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1003 (const unsigned char *) sig, size, &size));
1005 gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1007 gcry_mpi_release (val);
1008 bufSize = strlen (FORMATSTRING) + 1;
1009 buff = GNUNET_malloc (bufSize);
1010 memcpy (buff, FORMATSTRING, bufSize);
1012 [strlen (FORMATSTRING) -
1014 ("0123456789012345678901234567890123456789012345678901234567890123))")],
1015 &hc, sizeof (GNUNET_HashCode));
1016 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1018 hostkey = public2PrivateKey (publicKey);
1019 if (hostkey == NULL)
1021 gcry_sexp_release (data);
1022 gcry_sexp_release (sigdata);
1023 return GNUNET_SYSERR;
1025 rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
1026 GNUNET_CRYPTO_rsa_key_free (hostkey);
1027 gcry_sexp_release (data);
1028 gcry_sexp_release (sigdata);
1031 LOG (GNUNET_ERROR_TYPE_WARNING,
1032 _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1033 __LINE__, gcry_strerror (rc));
1034 return GNUNET_SYSERR;
1040 /* end of crypto_rsa.c */