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"
40 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
42 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
44 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
47 * The private information of an RSA key pair.
48 * NOTE: this must match the definition in crypto_ksk.c
50 struct GNUNET_CRYPTO_RsaPrivateKey
56 #define HOSTKEY_LEN 2048
58 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
62 * Log an error message at log-level 'level' that indicates
63 * a failure of the command 'cmd' with the message given
64 * by gcry_strerror(rc).
66 #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);
69 * If target != size, move target bytes to the
70 * end of the size-sized buffer and zero out the
71 * first target-size bytes.
74 adjust (unsigned char *buf, size_t size, size_t target)
78 memmove (&buf[target - size], buf, size);
79 memset (buf, 0, target - size);
84 * Create a new private key. Caller must free return value.
86 * @return fresh private key
88 struct GNUNET_CRYPTO_RsaPrivateKey *
89 GNUNET_CRYPTO_rsa_key_create ()
91 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
93 gcry_sexp_t s_keyparam;
96 gcry_sexp_build (&s_keyparam, NULL,
97 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
99 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
100 gcry_sexp_release (s_keyparam);
102 GNUNET_assert (0 == gcry_pk_testkey (s_key));
104 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
110 * Free memory occupied by hostkey
111 * @param hostkey pointer to the memory to free
114 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
116 gcry_sexp_release (hostkey->sexp);
117 GNUNET_free (hostkey);
121 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
124 gcry_sexp_t list, l2;
128 list = gcry_sexp_find_token (sexp, topname, 0);
133 l2 = gcry_sexp_cadr (list);
134 gcry_sexp_release (list);
142 for (s = elems; *s; s++, idx++)
144 l2 = gcry_sexp_find_token (list, s, 1);
147 for (i = 0; i < idx; i++)
149 gcry_free (array[i]);
152 gcry_sexp_release (list);
153 return 3; /* required parameter not found */
155 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
156 gcry_sexp_release (l2);
159 for (i = 0; i < idx; i++)
161 gcry_free (array[i]);
164 gcry_sexp_release (list);
165 return 4; /* required parameter is invalid */
168 gcry_sexp_release (list);
173 * Extract the public key of the host.
174 * @param priv the private key
175 * @param pub where to write the public key
178 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
180 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
187 rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
189 rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
191 rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
192 GNUNET_assert (0 == rc);
194 htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
195 sizeof (pub->padding));
196 pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
198 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
200 gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
202 adjust (&pub->key[0], size, GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
203 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
205 gcry_mpi_print (GCRYMPI_FMT_USG,
207 [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
209 adjust (&pub->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
210 GNUNET_CRYPTO_RSA_KEY_LENGTH -
211 GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
212 gcry_mpi_release (skey[0]);
213 gcry_mpi_release (skey[1]);
218 * Convert a public key to a string.
220 * @param pub key to convert
221 * @return string representing 'pub'
224 GNUNET_CRYPTO_rsa_public_key_to_string (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
227 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
231 keylen += 5 - keylen % 5;
233 pubkeybuf = GNUNET_malloc (keylen + 1);
234 end = GNUNET_STRINGS_data_to_string ((unsigned char *) &pub,
235 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
240 GNUNET_free (pubkeybuf);
249 * Convert a string representing a public key to a public key.
251 * @param enc encoded public key
252 * @param enclen number of bytes in enc (without 0-terminator)
253 * @param pub where to store the public key
254 * @return GNUNET_OK on success
257 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc,
259 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
261 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
264 keylen += 5 - keylen % 5;
266 if (enclen != keylen)
267 return GNUNET_SYSERR;
269 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
270 (unsigned char*) pub,
271 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
272 return GNUNET_SYSERR;
273 if ( (ntohs (pub->len) != sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) ||
274 (ntohs (pub->padding) != 0) ||
275 (ntohs (pub->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) )
276 return GNUNET_SYSERR;
282 * Internal: publicKey => RSA-Key.
284 * Note that the return type is not actually a private
285 * key but rather an sexpression for the public key!
287 static struct GNUNET_CRYPTO_RsaPrivateKey *
288 public2PrivateKey (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
291 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
299 if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
300 (ntohs (publicKey->len) !=
301 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
302 sizeof (publicKey->padding)))
307 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
308 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
311 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
314 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
315 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
316 &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
320 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
321 gcry_mpi_release (n);
324 rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
326 gcry_mpi_release (n);
327 gcry_mpi_release (e);
330 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
333 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
340 * Encode the private key in a format suitable for
341 * storing it into a file.
342 * @returns encoding of the private key.
343 * The first 4 bytes give the size of the array, as usual.
345 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
346 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
348 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *retval;
357 if (gcry_pk_testkey (hostkey->sexp))
364 memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
365 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
367 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
369 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
371 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
373 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
375 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
376 GNUNET_assert (0 == rc);
377 size = sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded);
378 for (i = 0; i < 6; i++)
383 gcry_mpi_aprint (GCRYMPI_FMT_USG,
384 (unsigned char **) &pbu[i], &sizes[i],
394 GNUNET_assert (size < 65536);
395 retval = GNUNET_malloc (size);
396 retval->len = htons (size);
398 retval->sizen = htons (sizes[0]);
399 memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
401 retval->sizee = htons (sizes[1]);
402 memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
404 retval->sized = htons (sizes[2]);
405 memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
408 retval->sizep = htons (sizes[4]);
409 memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
411 retval->sizeq = htons (sizes[3]);
412 memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
414 retval->sizedmp1 = htons (0);
415 retval->sizedmq1 = htons (0);
416 memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
417 for (i = 0; i < 6; i++)
420 gcry_mpi_release (pkv[i]);
429 * Decode the private key from the file-format back
430 * to the "normal", internal format.
432 * @param buf the buffer where the private key data is stored
433 * @param len the length of the data in 'buffer'
435 struct GNUNET_CRYPTO_RsaPrivateKey *
436 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
438 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
439 const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *encoding =
440 (const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *) buf;
442 gcry_mpi_t n, e, d, p, q, u;
448 enc_len = ntohs (encoding->len);
453 size = ntohs (encoding->sizen);
454 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
455 &((const unsigned char *) (&encoding[1]))[pos], size,
457 pos += ntohs (encoding->sizen);
460 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
463 size = ntohs (encoding->sizee);
464 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
465 &((const unsigned char *) (&encoding[1]))[pos], size,
467 pos += ntohs (encoding->sizee);
470 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
471 gcry_mpi_release (n);
474 size = ntohs (encoding->sized);
475 rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
476 &((const unsigned char *) (&encoding[1]))[pos], size,
478 pos += ntohs (encoding->sized);
481 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
482 gcry_mpi_release (n);
483 gcry_mpi_release (e);
487 size = ntohs (encoding->sizep);
490 rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
491 &((const unsigned char *) (&encoding[1]))[pos], size,
493 pos += ntohs (encoding->sizep);
496 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
497 gcry_mpi_release (n);
498 gcry_mpi_release (e);
499 gcry_mpi_release (d);
505 size = ntohs (encoding->sizeq);
508 rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
509 &((const unsigned char *) (&encoding[1]))[pos], size,
511 pos += ntohs (encoding->sizeq);
514 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
515 gcry_mpi_release (n);
516 gcry_mpi_release (e);
517 gcry_mpi_release (d);
519 gcry_mpi_release (q);
525 pos += ntohs (encoding->sizedmp1);
526 pos += ntohs (encoding->sizedmq1);
528 ntohs (encoding->len) - sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded) - pos;
531 rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
532 &((const unsigned char *) (&encoding[1]))[pos], size,
536 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
537 gcry_mpi_release (n);
538 gcry_mpi_release (e);
539 gcry_mpi_release (d);
541 gcry_mpi_release (p);
543 gcry_mpi_release (q);
550 if ((p != NULL) && (q != NULL) && (u != NULL))
552 rc = gcry_sexp_build (&res, &size, /* erroff */
553 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
558 if ((p != NULL) && (q != NULL))
560 rc = gcry_sexp_build (&res, &size, /* erroff */
561 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
566 rc = gcry_sexp_build (&res, &size, /* erroff */
567 "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
570 gcry_mpi_release (n);
571 gcry_mpi_release (e);
572 gcry_mpi_release (d);
574 gcry_mpi_release (p);
576 gcry_mpi_release (q);
578 gcry_mpi_release (u);
581 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
583 if (gcry_pk_testkey (res))
585 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
589 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
596 * Create a new private key by reading it from a file. If the
597 * files does not exist, create a new key and write it to the
598 * file. Caller must free return value. Note that this function
599 * can not guarantee that another process might not be trying
600 * the same operation on the same file at the same time.
601 * If the contents of the file
602 * are invalid the old file is deleted and a fresh key is
605 * @return new private key, NULL on error (for example,
608 struct GNUNET_CRYPTO_RsaPrivateKey *
609 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
611 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
612 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
614 struct GNUNET_DISK_FileHandle *fd;
618 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
619 struct GNUNET_PeerIdentity pid;
621 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
623 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
625 fd = GNUNET_DISK_file_open (filename,
626 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
627 | GNUNET_DISK_OPEN_FAILIFEXISTS,
628 GNUNET_DISK_PERM_USER_READ |
629 GNUNET_DISK_PERM_USER_WRITE);
634 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
636 /* must exist but not be accessible, fail for good! */
637 if (0 != ACCESS (filename, R_OK))
638 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
640 GNUNET_break (0); /* what is going on!? */
645 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
651 GNUNET_DISK_file_lock (fd, 0,
652 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
659 LOG (GNUNET_ERROR_TYPE_ERROR,
660 _("Could not aquire lock on file `%s': %s...\n"), filename,
664 LOG (GNUNET_ERROR_TYPE_INFO,
665 _("Creating a new private key. This may take a while.\n"));
666 ret = GNUNET_CRYPTO_rsa_key_create ();
667 GNUNET_assert (ret != NULL);
668 enc = GNUNET_CRYPTO_rsa_encode_key (ret);
669 GNUNET_assert (enc != NULL);
670 GNUNET_assert (ntohs (enc->len) ==
671 GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
674 GNUNET_DISK_file_sync (fd);
676 GNUNET_DISK_file_unlock (fd, 0,
677 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
678 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
679 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
680 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
681 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
682 LOG (GNUNET_ERROR_TYPE_INFO,
683 _("I am host `%s'. Stored new private key in `%s'.\n"),
684 GNUNET_i2s (&pid), filename);
687 /* hostkey file exists already, read it! */
688 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
689 GNUNET_DISK_PERM_NONE);
692 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
699 GNUNET_DISK_file_lock (fd, 0,
700 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
706 LOG (GNUNET_ERROR_TYPE_ERROR,
707 _("Could not aquire lock on file `%s': %s...\n"), filename,
709 LOG (GNUNET_ERROR_TYPE_ERROR,
711 ("This may be ok if someone is currently generating a hostkey.\n"));
716 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
718 /* eh, what!? File we opened is now gone!? */
719 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
721 GNUNET_DISK_file_unlock (fd, 0,
722 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
723 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
724 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
728 if (GNUNET_YES != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES))
730 if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
732 /* maybe we got the read lock before the hostkey generating
733 * process had a chance to get the write lock; give it up! */
735 GNUNET_DISK_file_unlock (fd, 0,
736 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
737 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
740 LOG (GNUNET_ERROR_TYPE_ERROR,
742 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
743 filename, (unsigned int) fs,
744 (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
745 LOG (GNUNET_ERROR_TYPE_ERROR,
747 ("This may be ok if someone is currently generating a hostkey.\n"));
749 sleep (2); /* wait a bit longer! */
754 enc = GNUNET_malloc (fs);
755 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
756 len = ntohs (enc->len);
759 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
761 LOG (GNUNET_ERROR_TYPE_ERROR,
762 _("File `%s' does not contain a valid private key. Deleting it.\n"),
764 if (0 != UNLINK (filename))
766 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
771 GNUNET_DISK_file_unlock (fd, 0,
772 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
773 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
774 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
777 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
778 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
779 LOG (GNUNET_ERROR_TYPE_INFO,
780 _("I am host `%s'. Read private key from `%s'.\n"), GNUNET_i2s (&pid),
788 * Setup a hostkey file for a peer given the name of the
789 * configuration file (!). This function is used so that
790 * at a later point code can be certain that reading a
791 * hostkey is fast (for example in time-dependent testcases).
793 * @param cfg_name name of the configuration file to use
796 GNUNET_CRYPTO_setup_hostkey (const char *cfg_name)
798 struct GNUNET_CONFIGURATION_Handle *cfg;
799 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
802 cfg = GNUNET_CONFIGURATION_create ();
803 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
805 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
807 pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
809 GNUNET_CRYPTO_rsa_key_free (pk);
811 GNUNET_CONFIGURATION_destroy (cfg);
816 * Encrypt a block with the public key of another host that uses the
819 * @param block the block to encrypt
820 * @param size the size of block
821 * @param publicKey the encoded public key used to encrypt
822 * @param target where to store the encrypted block
823 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
826 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
827 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
829 struct GNUNET_CRYPTO_RsaEncryptedData *target)
833 struct GNUNET_CRYPTO_RsaPrivateKey *pubkey;
839 GNUNET_assert (size <= sizeof (GNUNET_HashCode));
840 pubkey = public2PrivateKey (publicKey);
842 return GNUNET_SYSERR;
845 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
847 gcry_sexp_build (&data, &erroff,
848 "(data (flags pkcs1)(value %m))", val));
849 gcry_mpi_release (val);
850 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, pubkey->sexp));
851 gcry_sexp_release (data);
852 GNUNET_CRYPTO_rsa_key_free (pubkey);
854 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
855 gcry_sexp_release (result);
856 isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
858 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
859 isize, &isize, rval));
860 gcry_mpi_release (rval);
861 adjust (&target->encoding[0], isize,
862 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
868 * Decrypt a given block with the hostkey.
870 * @param key the key with which to decrypt this block
871 * @param block the data to decrypt, encoded as returned by encrypt
872 * @param result pointer to a location where the result can be stored
873 * @param max the maximum number of bits to store for the result, if
874 * the decrypted block is bigger, an error is returned
875 * @return the size of the decrypted block, -1 on error
878 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
879 const struct GNUNET_CRYPTO_RsaEncryptedData * block,
880 void *result, size_t max)
882 gcry_sexp_t resultsexp;
891 GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
893 size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
895 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
898 gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
900 gcry_mpi_release (val);
901 GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
902 gcry_sexp_release (data);
903 /* resultsexp has format "(value %m)" */
904 GNUNET_assert (NULL !=
905 (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
906 gcry_sexp_release (resultsexp);
907 tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
908 size = max + HOSTKEY_LEN / 8;
909 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
910 gcry_mpi_release (val);
912 endp += (size - max);
914 memcpy (result, endp, size);
921 * Sign a given block.
923 * @param key private key to use for the signing
924 * @param purpose what to sign (size, purpose)
925 * @param sig where to write the signature
926 * @return GNUNET_SYSERR on error, GNUNET_OK on success
929 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
930 const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
931 struct GNUNET_CRYPTO_RsaSignature *sig)
941 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
942 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
943 bufSize = strlen (FORMATSTRING) + 1;
944 buff = GNUNET_malloc (bufSize);
945 memcpy (buff, FORMATSTRING, bufSize);
949 ("0123456789012345678901234567890123456789012345678901234567890123))")
950 - 1], &hc, sizeof (GNUNET_HashCode));
951 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
953 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
954 gcry_sexp_release (data);
955 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
956 gcry_sexp_release (result);
957 ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
959 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
961 gcry_mpi_release (rval);
962 adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
970 * @param purpose what is the purpose that the signature should have?
971 * @param validate block to validate (size, purpose, data)
972 * @param sig signature that is being validated
973 * @param publicKey public key of the signer
974 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
977 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
978 const struct GNUNET_CRYPTO_RsaSignaturePurpose
980 const struct GNUNET_CRYPTO_RsaSignature *sig,
981 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
988 struct GNUNET_CRYPTO_RsaPrivateKey *hostkey;
995 if (purpose != ntohl (validate->purpose))
996 return GNUNET_SYSERR; /* purpose mismatch */
997 GNUNET_CRYPTO_hash (validate, ntohl (validate->size), &hc);
998 size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1000 gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1001 (const unsigned char *) sig, size, &size));
1003 gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1005 gcry_mpi_release (val);
1006 bufSize = strlen (FORMATSTRING) + 1;
1007 buff = GNUNET_malloc (bufSize);
1008 memcpy (buff, FORMATSTRING, bufSize);
1010 [strlen (FORMATSTRING) -
1012 ("0123456789012345678901234567890123456789012345678901234567890123))")],
1013 &hc, sizeof (GNUNET_HashCode));
1014 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1016 hostkey = public2PrivateKey (publicKey);
1017 if (hostkey == NULL)
1019 gcry_sexp_release (data);
1020 gcry_sexp_release (sigdata);
1021 return GNUNET_SYSERR;
1023 rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
1024 GNUNET_CRYPTO_rsa_key_free (hostkey);
1025 gcry_sexp_release (data);
1026 gcry_sexp_release (sigdata);
1029 LOG (GNUNET_ERROR_TYPE_WARNING,
1030 _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1031 __LINE__, gcry_strerror (rc));
1032 return GNUNET_SYSERR;
1038 /* end of crypto_rsa.c */