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
28 #include "gnunet_common.h"
29 #include "gnunet_util_lib.h"
31 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
35 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
37 #define HOSTKEY_LEN 2048
39 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
43 * The private information of an RSA key pair.
44 * NOTE: this must match the definition in crypto_ksk.c and gnunet-rsa.c!
46 struct GNUNET_CRYPTO_RsaPrivateKey
49 * Libgcrypt S-expression for the ECC key.
55 * Log an error message at log-level 'level' that indicates
56 * a failure of the command 'cmd' with the message given
57 * by gcry_strerror(rc).
59 #define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0);
62 * If target != size, move target bytes to the
63 * end of the size-sized buffer and zero out the
64 * first target-size bytes.
66 * @param buf original buffer
67 * @param size number of bytes in the buffer
68 * @param target target size of the buffer
71 adjust (unsigned char *buf, size_t size, size_t target)
75 memmove (&buf[target - size], buf, size);
76 memset (buf, 0, target - size);
82 * Free memory occupied by RSA private key.
84 * @param key pointer to the memory to free
87 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *key)
89 gcry_sexp_release (key->sexp);
95 * Extract values from an S-expression.
97 * @param array where to store the result(s)
98 * @param sexp S-expression to parse
99 * @param topname top-level name in the S-expression that is of interest
100 * @param elems names of the elements to extract
101 * @return 0 on success
104 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
113 if (! (list = gcry_sexp_find_token (sexp, topname, 0)))
115 l2 = gcry_sexp_cadr (list);
116 gcry_sexp_release (list);
121 for (s = elems; *s; s++, idx++)
123 if (! (l2 = gcry_sexp_find_token (list, s, 1)))
125 for (i = 0; i < idx; i++)
127 gcry_free (array[i]);
130 gcry_sexp_release (list);
131 return 3; /* required parameter not found */
133 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
134 gcry_sexp_release (l2);
137 for (i = 0; i < idx; i++)
139 gcry_free (array[i]);
142 gcry_sexp_release (list);
143 return 4; /* required parameter is invalid */
146 gcry_sexp_release (list);
152 * Extract the public key of the host.
154 * @param priv the private key
155 * @param pub where to write the public key
158 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
160 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
167 rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
169 rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
171 rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
172 GNUNET_assert (0 == rc);
174 htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
175 sizeof (pub->padding));
176 pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
178 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
180 gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
182 adjust (&pub->key[0], size, GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
183 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
185 gcry_mpi_print (GCRYMPI_FMT_USG,
187 [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
189 adjust (&pub->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
190 GNUNET_CRYPTO_RSA_KEY_LENGTH -
191 GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
192 gcry_mpi_release (skey[0]);
193 gcry_mpi_release (skey[1]);
198 * Get hash of the public key that corresponds to a private key.
200 * @param key RSA private key
201 * @param id buffer for hash of the public key
204 GNUNET_CRYPTO_rsa_get_public_key_hash (struct GNUNET_CRYPTO_RsaPrivateKey *key,
205 struct GNUNET_HashCode *id)
207 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
208 GNUNET_CRYPTO_rsa_key_get_public (key, &pk);
209 GNUNET_CRYPTO_hash (&pk, sizeof (pk), id);
214 * Convert a public key to a string.
216 * @param pub key to convert
217 * @return string representing 'pub'
220 GNUNET_CRYPTO_rsa_public_key_to_string (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
223 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
227 keylen += 5 - keylen % 5;
229 pubkeybuf = GNUNET_malloc (keylen + 1);
230 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
231 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
236 GNUNET_free (pubkeybuf);
245 * Convert a string representing a public key to a public key.
247 * @param enc encoded public key
248 * @param enclen number of bytes in enc (without 0-terminator)
249 * @param pub where to store the public key
250 * @return GNUNET_OK on success
253 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc,
255 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
257 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
260 keylen += 5 - keylen % 5;
262 if (enclen != keylen)
263 return GNUNET_SYSERR;
265 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
266 (unsigned char*) pub,
267 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
268 return GNUNET_SYSERR;
269 if ( (ntohs (pub->len) != sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) ||
270 (ntohs (pub->padding) != 0) ||
271 (ntohs (pub->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) )
272 return GNUNET_SYSERR;
278 * Convert the given public key from the network format to the
279 * S-expression that can be used by libgcrypt.
281 * @param publicKey public key to decode
282 * @return NULL on error
285 decode_public_key (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
294 if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
295 (ntohs (publicKey->len) !=
296 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
297 sizeof (publicKey->padding)))
302 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
303 if (0 != (rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size)))
305 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
308 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
309 if (0 != (rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
310 &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
313 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
314 gcry_mpi_release (n);
317 rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
319 gcry_mpi_release (n);
320 gcry_mpi_release (e);
323 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
331 * Encode the private key in a format suitable for
332 * storing it into a file.
334 * @return encoding of the private key.
335 * The first 4 bytes give the size of the array, as usual.
337 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
338 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
340 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *retval;
349 if (gcry_pk_testkey (hostkey->sexp))
356 memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
357 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
359 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
361 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
363 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
365 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
367 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
368 GNUNET_assert (0 == rc);
369 size = sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded);
370 for (i = 0; i < 6; i++)
375 gcry_mpi_aprint (GCRYMPI_FMT_USG,
376 (unsigned char **) &pbu[i], &sizes[i],
386 GNUNET_assert (size < 65536);
387 retval = GNUNET_malloc (size);
388 retval->len = htons (size);
390 retval->sizen = htons (sizes[0]);
391 memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
393 retval->sizee = htons (sizes[1]);
394 memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
396 retval->sized = htons (sizes[2]);
397 memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
400 retval->sizep = htons (sizes[4]);
401 memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
403 retval->sizeq = htons (sizes[3]);
404 memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
406 retval->sizedmp1 = htons (0);
407 retval->sizedmq1 = htons (0);
408 memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
409 for (i = 0; i < 6; i++)
412 gcry_mpi_release (pkv[i]);
421 * Decode the private key from the file-format back
422 * to the "normal", internal format.
424 * @param buf the buffer where the private key data is stored
425 * @param len the length of the data in 'buffer'
426 * @return NULL on error
428 struct GNUNET_CRYPTO_RsaPrivateKey *
429 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
431 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
432 const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *encoding =
433 (const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *) buf;
447 enc_len = ntohs (encoding->len);
452 size = ntohs (encoding->sizen);
453 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
454 &((const unsigned char *) (&encoding[1]))[pos], size,
456 pos += ntohs (encoding->sizen);
459 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
462 size = ntohs (encoding->sizee);
463 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
464 &((const unsigned char *) (&encoding[1]))[pos], size,
466 pos += ntohs (encoding->sizee);
469 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
470 gcry_mpi_release (n);
473 size = ntohs (encoding->sized);
474 rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
475 &((const unsigned char *) (&encoding[1]))[pos], size,
477 pos += ntohs (encoding->sized);
480 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
481 gcry_mpi_release (n);
482 gcry_mpi_release (e);
486 size = ntohs (encoding->sizep);
489 rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
490 &((const unsigned char *) (&encoding[1]))[pos], size,
492 pos += ntohs (encoding->sizep);
495 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
496 gcry_mpi_release (n);
497 gcry_mpi_release (e);
498 gcry_mpi_release (d);
504 size = ntohs (encoding->sizeq);
507 rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
508 &((const unsigned char *) (&encoding[1]))[pos], size,
510 pos += ntohs (encoding->sizeq);
513 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
514 gcry_mpi_release (n);
515 gcry_mpi_release (e);
516 gcry_mpi_release (d);
518 gcry_mpi_release (q);
524 pos += ntohs (encoding->sizedmp1);
525 pos += ntohs (encoding->sizedmq1);
527 ntohs (encoding->len) - sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded) - pos;
530 rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
531 &((const unsigned char *) (&encoding[1]))[pos], size,
535 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
536 gcry_mpi_release (n);
537 gcry_mpi_release (e);
538 gcry_mpi_release (d);
540 gcry_mpi_release (p);
542 gcry_mpi_release (q);
549 if ((NULL != p) && (NULL != q) && (NULL != u))
551 rc = gcry_sexp_build (&res, &erroff,
552 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
557 if ((NULL != p) && (NULL != q))
559 rc = gcry_sexp_build (&res, &erroff,
560 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
565 rc = gcry_sexp_build (&res, &erroff,
566 "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
569 gcry_mpi_release (n);
570 gcry_mpi_release (e);
571 gcry_mpi_release (d);
573 gcry_mpi_release (p);
575 gcry_mpi_release (q);
577 gcry_mpi_release (u);
580 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
582 if (0 != (rc = gcry_pk_testkey (res)))
584 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
588 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
595 * Create a new private key. Caller must free return value.
597 * @return fresh private key
599 static struct GNUNET_CRYPTO_RsaPrivateKey *
602 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
604 gcry_sexp_t s_keyparam;
607 gcry_sexp_build (&s_keyparam, NULL,
608 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
610 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
611 gcry_sexp_release (s_keyparam);
613 GNUNET_assert (0 == gcry_pk_testkey (s_key));
615 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
622 * Try to read the private key from the given file.
624 * @param filename file to read the key from
625 * @return NULL on error
627 static struct GNUNET_CRYPTO_RsaPrivateKey *
628 try_read_key (const char *filename)
630 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
631 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
632 struct GNUNET_DISK_FileHandle *fd;
636 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
639 /* hostkey file exists already, read it! */
640 if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
641 GNUNET_DISK_PERM_NONE)))
643 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
646 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
648 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
649 (void) GNUNET_DISK_file_close (fd);
654 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
659 LOG (GNUNET_ERROR_TYPE_ERROR,
660 _("File `%s' does not contain a valid private key (too long, %llu bytes). Renaming it.\n"),
662 (unsigned long long) fs);
663 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
664 GNUNET_DISK_file_backup (filename);
668 enc = GNUNET_malloc (fs);
669 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
670 len = ntohs (enc->len);
673 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
675 LOG (GNUNET_ERROR_TYPE_ERROR,
676 _("File `%s' does not contain a valid private key (failed decode, %llu bytes). Deleting it.\n"),
678 (unsigned long long) fs);
679 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
680 GNUNET_DISK_file_backup (filename);
686 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
692 * Wait for a short time (we're trying to lock a file or want
693 * to give another process a shot at finishing a disk write, etc.).
694 * Sleeps for 100ms (as that should be long enough for virtually all
695 * modern systems to context switch and allow another process to do
701 struct GNUNET_TIME_Relative timeout;
703 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
704 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
709 * Open existing private key file and read it. If the
710 * file does not exist, or the contents of the file are
711 * invalid, the function fails
712 * Caller must free returned value.
714 * @return a private key, NULL on error (for example,
715 * permission denied) or when file does not exist or contains invalid
718 struct GNUNET_CRYPTO_RsaPrivateKey *
719 GNUNET_CRYPTO_rsa_key_create_from_existing_file (const char *filename)
721 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
722 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
724 struct GNUNET_DISK_FileHandle *fd;
728 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
729 struct GNUNET_PeerIdentity pid;
731 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
732 GNUNET_DISK_PERM_NONE);
735 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
742 GNUNET_DISK_file_lock (fd, 0,
743 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
749 LOG (GNUNET_ERROR_TYPE_ERROR,
750 _("Could not acquire lock on file `%s': %s...\n"), filename,
752 LOG (GNUNET_ERROR_TYPE_ERROR,
754 ("This may be ok if someone is currently generating a private key.\n"));
759 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
761 /* eh, what!? File we opened is now gone!? */
762 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
764 GNUNET_DISK_file_unlock (fd, 0,
765 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
766 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
767 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
771 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
773 if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
775 /* maybe we got the read lock before the key generating
776 * process had a chance to get the write lock; give it up! */
778 GNUNET_DISK_file_unlock (fd, 0,
779 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
780 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
783 LOG (GNUNET_ERROR_TYPE_ERROR,
785 ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
786 filename, (unsigned int) fs,
787 (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
788 LOG (GNUNET_ERROR_TYPE_ERROR,
790 ("This may be ok if someone is currently generating a private key.\n"));
792 short_wait (); /* wait a bit longer! */
797 enc = GNUNET_malloc (fs);
798 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
799 len = ntohs (enc->len);
802 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
804 LOG (GNUNET_ERROR_TYPE_ERROR,
805 _("File `%s' does not contain a valid private key. Deleting it.\n"),
807 GNUNET_DISK_file_backup (filename);
811 GNUNET_DISK_file_unlock (fd, 0,
812 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
813 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
814 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
817 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
818 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
824 * Create a new private key by reading it from a file. If the
825 * files does not exist, create a new key and write it to the
826 * file. Caller must free return value. Note that this function
827 * can not guarantee that another process might not be trying
828 * the same operation on the same file at the same time.
829 * If the contents of the file
830 * are invalid the old file is deleted and a fresh key is
833 * @return new private key, NULL on error (for example,
836 struct GNUNET_CRYPTO_RsaPrivateKey *
837 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
839 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
840 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
841 struct GNUNET_DISK_FileHandle *fd;
844 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
845 struct GNUNET_PeerIdentity pid;
847 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
850 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
852 fd = GNUNET_DISK_file_open (filename,
853 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
854 | GNUNET_DISK_OPEN_FAILIFEXISTS,
855 GNUNET_DISK_PERM_USER_READ |
856 GNUNET_DISK_PERM_USER_WRITE);
861 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
863 /* must exist but not be accessible, fail for good! */
864 if (0 != ACCESS (filename, R_OK))
865 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
867 GNUNET_break (0); /* what is going on!? */
872 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
878 GNUNET_DISK_file_lock (fd, 0,
879 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
886 LOG (GNUNET_ERROR_TYPE_ERROR,
887 _("Could not acquire lock on file `%s': %s...\n"), filename,
891 LOG (GNUNET_ERROR_TYPE_INFO,
892 _("Creating a new private key. This may take a while.\n"));
893 ret = rsa_key_create ();
894 GNUNET_assert (ret != NULL);
895 enc = GNUNET_CRYPTO_rsa_encode_key (ret);
896 GNUNET_assert (enc != NULL);
897 GNUNET_assert (ntohs (enc->len) ==
898 GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
901 GNUNET_DISK_file_sync (fd);
903 GNUNET_DISK_file_unlock (fd, 0,
904 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
905 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
906 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
907 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
908 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
911 /* hostkey file exists already, read it! */
912 return GNUNET_CRYPTO_rsa_key_create_from_existing_file (filename);
917 * Handle to cancel private key generation and state for the
918 * key generation operation.
920 struct GNUNET_CRYPTO_RsaKeyGenerationContext
924 * Continuation to call upon completion.
926 GNUNET_CRYPTO_RsaKeyCallback cont;
929 * Closure for 'cont'.
939 * Handle to the helper process which does the key generation.
941 struct GNUNET_OS_Process *gnunet_rsa;
944 * Handle to 'stdout' of gnunet-rsa. We 'read' on stdout to detect
945 * process termination (instead of messing with SIGCHLD).
947 struct GNUNET_DISK_PipeHandle *gnunet_rsa_out;
950 * Location where we store the private key if it already existed.
951 * (if this is used, 'filename', 'gnunet_rsa' and 'gnunet_rsa_out' will
954 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
957 * Task reading from 'gnunet_rsa_out' to wait for process termination.
959 GNUNET_SCHEDULER_TaskIdentifier read_task;
965 * Task called upon shutdown or process termination of 'gnunet-rsa' during
966 * RSA key generation. Check where we are and perform the appropriate
969 * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
970 * @param tc scheduler context
973 check_key_generation_completion (void *cls,
974 const struct GNUNET_SCHEDULER_TaskContext *tc)
976 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
977 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
979 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
980 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
982 gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
983 GNUNET_CRYPTO_rsa_key_create_stop (gc);
986 GNUNET_assert (GNUNET_OK ==
987 GNUNET_OS_process_wait (gc->gnunet_rsa));
988 GNUNET_OS_process_destroy (gc->gnunet_rsa);
989 gc->gnunet_rsa = NULL;
990 if (NULL == (pk = try_read_key (gc->filename)))
993 gc->cont (gc->cont_cls, NULL, _("gnunet-rsa failed"));
994 GNUNET_CRYPTO_rsa_key_create_stop (gc);
997 gc->cont (gc->cont_cls, pk, NULL);
998 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
999 GNUNET_free (gc->filename);
1005 * Return the private RSA key which already existed on disk
1006 * (asynchronously) to the caller.
1008 * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
1009 * @param tc scheduler context (unused)
1012 async_return_key (void *cls,
1013 const struct GNUNET_SCHEDULER_TaskContext *tc)
1015 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
1017 gc->cont (gc->cont_cls,
1025 * Create a new private key by reading it from a file. If the files
1026 * does not exist, create a new key and write it to the file. If the
1027 * contents of the file are invalid the old file is deleted and a
1028 * fresh key is created.
1030 * @param filename name of file to use for storage
1031 * @param cont function to call when done (or on errors)
1032 * @param cont_cls closure for 'cont'
1033 * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
1035 struct GNUNET_CRYPTO_RsaKeyGenerationContext *
1036 GNUNET_CRYPTO_rsa_key_create_start (const char *filename,
1037 GNUNET_CRYPTO_RsaKeyCallback cont,
1040 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc;
1041 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1043 if (NULL != (pk = try_read_key (filename)))
1045 /* quick happy ending: key already exists! */
1046 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1049 gc->cont_cls = cont_cls;
1050 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
1054 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1055 gc->filename = GNUNET_strdup (filename);
1057 gc->cont_cls = cont_cls;
1058 gc->gnunet_rsa_out = GNUNET_DISK_pipe (GNUNET_NO,
1062 if (NULL == gc->gnunet_rsa_out)
1064 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
1065 GNUNET_free (gc->filename);
1069 gc->gnunet_rsa = GNUNET_OS_start_process (GNUNET_NO,
1070 GNUNET_OS_INHERIT_STD_ERR,
1077 if (NULL == gc->gnunet_rsa)
1079 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
1080 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1081 GNUNET_free (gc->filename);
1085 GNUNET_assert (GNUNET_OK ==
1086 GNUNET_DISK_pipe_close_end (gc->gnunet_rsa_out,
1087 GNUNET_DISK_PIPE_END_WRITE));
1088 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1089 GNUNET_DISK_pipe_handle (gc->gnunet_rsa_out,
1090 GNUNET_DISK_PIPE_END_READ),
1091 &check_key_generation_completion,
1098 * Abort RSA key generation.
1100 * @param gc key generation context to abort
1103 GNUNET_CRYPTO_rsa_key_create_stop (struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc)
1105 if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
1107 GNUNET_SCHEDULER_cancel (gc->read_task);
1108 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
1110 if (NULL != gc->gnunet_rsa)
1112 (void) GNUNET_OS_process_kill (gc->gnunet_rsa, SIGKILL);
1113 GNUNET_break (GNUNET_OK ==
1114 GNUNET_OS_process_wait (gc->gnunet_rsa));
1115 GNUNET_OS_process_destroy (gc->gnunet_rsa);
1116 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1119 if (NULL != gc->filename)
1121 if (0 != UNLINK (gc->filename))
1122 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
1123 GNUNET_free (gc->filename);
1126 GNUNET_CRYPTO_rsa_key_free (gc->pk);
1132 * Setup a key file for a peer given the name of the
1133 * configuration file (!). This function is used so that
1134 * at a later point code can be certain that reading a
1135 * key is fast (for example in time-dependent testcases).
1137 * @param cfg_name name of the configuration file to use
1140 GNUNET_CRYPTO_rsa_setup_hostkey (const char *cfg_name)
1142 struct GNUNET_CONFIGURATION_Handle *cfg;
1143 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1146 cfg = GNUNET_CONFIGURATION_create ();
1147 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
1149 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
1151 pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
1153 GNUNET_CRYPTO_rsa_key_free (pk);
1156 GNUNET_CONFIGURATION_destroy (cfg);
1161 * Encrypt a block with the public key of another host that uses the
1164 * @param block the block to encrypt
1165 * @param size the size of block
1166 * @param publicKey the encoded public key used to encrypt
1167 * @param target where to store the encrypted block
1168 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
1171 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
1172 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1174 struct GNUNET_CRYPTO_RsaEncryptedData *target)
1184 GNUNET_assert (size <= sizeof (struct GNUNET_HashCode));
1185 if (! (psexp = decode_public_key (publicKey)))
1186 return GNUNET_SYSERR;
1189 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
1191 gcry_sexp_build (&data, &erroff,
1192 "(data (flags pkcs1)(value %m))", val));
1193 gcry_mpi_release (val);
1194 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, psexp));
1195 gcry_sexp_release (data);
1196 gcry_sexp_release (psexp);
1197 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
1198 gcry_sexp_release (result);
1199 isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1201 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
1202 isize, &isize, rval));
1203 gcry_mpi_release (rval);
1204 adjust (&target->encoding[0], isize,
1205 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
1211 * Decrypt a given block with the key.
1213 * @param key the key with which to decrypt this block
1214 * @param block the data to decrypt, encoded as returned by encrypt
1215 * @param result pointer to a location where the result can be stored
1216 * @param max the maximum number of bits to store for the result, if
1217 * the decrypted block is bigger, an error is returned
1218 * @return the size of the decrypted block, -1 on error
1221 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
1222 const struct GNUNET_CRYPTO_RsaEncryptedData * block,
1223 void *result, size_t max)
1225 gcry_sexp_t resultsexp;
1230 unsigned char *endp;
1234 GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
1236 size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1238 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
1241 gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
1243 gcry_mpi_release (val);
1244 GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
1245 gcry_sexp_release (data);
1246 /* resultsexp has format "(value %m)" */
1247 GNUNET_assert (NULL !=
1248 (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
1249 gcry_sexp_release (resultsexp);
1250 tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
1251 size = max + HOSTKEY_LEN / 8;
1252 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
1253 gcry_mpi_release (val);
1255 endp += (size - max);
1257 memcpy (result, endp, size);
1264 * Convert the data specified in the given purpose argument to an
1265 * S-expression suitable for signature operations.
1267 * @param purpose data to convert
1268 * @return converted s-expression
1271 data_to_pkcs1 (const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose)
1273 struct GNUNET_HashCode hc;
1277 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1278 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
1279 bufSize = strlen (FORMATSTRING) + 1;
1283 memcpy (buff, FORMATSTRING, bufSize);
1287 ("0123456789012345678901234567890123456789012345678901234567890123))")
1288 - 1], &hc, sizeof (struct GNUNET_HashCode));
1289 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1297 * Sign a given block.
1299 * @param key private key to use for the signing
1300 * @param purpose what to sign (size, purpose)
1301 * @param sig where to write the signature
1302 * @return GNUNET_SYSERR on error, GNUNET_OK on success
1305 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1306 const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
1307 struct GNUNET_CRYPTO_RsaSignature *sig)
1314 data = data_to_pkcs1 (purpose);
1315 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
1316 gcry_sexp_release (data);
1317 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
1318 gcry_sexp_release (result);
1319 ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1321 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
1323 gcry_mpi_release (rval);
1324 adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
1332 * @param purpose what is the purpose that the signature should have?
1333 * @param validate block to validate (size, purpose, data)
1334 * @param sig signature that is being validated
1335 * @param publicKey public key of the signer
1336 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1339 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
1340 const struct GNUNET_CRYPTO_RsaSignaturePurpose
1342 const struct GNUNET_CRYPTO_RsaSignature *sig,
1343 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1347 gcry_sexp_t sigdata;
1354 if (purpose != ntohl (validate->purpose))
1355 return GNUNET_SYSERR; /* purpose mismatch */
1356 size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1358 gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1359 (const unsigned char *) sig, size, &size));
1361 gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1363 gcry_mpi_release (val);
1364 data = data_to_pkcs1 (validate);
1365 if (! (psexp = decode_public_key (publicKey)))
1367 gcry_sexp_release (data);
1368 gcry_sexp_release (sigdata);
1369 return GNUNET_SYSERR;
1371 rc = gcry_pk_verify (sigdata, data, psexp);
1372 gcry_sexp_release (psexp);
1373 gcry_sexp_release (data);
1374 gcry_sexp_release (sigdata);
1377 LOG (GNUNET_ERROR_TYPE_WARNING,
1378 _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1379 __LINE__, gcry_strerror (rc));
1380 return GNUNET_SYSERR;
1386 /* end of crypto_rsa.c */