2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009, 2012 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_ecc.c
23 * @brief public key cryptography (ECC) with libgcrypt
24 * @author Christian Grothoff
26 * This is just a first, completely untested, draft hack for future ECC support.
28 * - declare public API in gnunet_crypto_lib (move some structs, etc.)
29 * - implement gnunet-ecc binary
30 * - convert existing RSA testcases
31 * - adjust encoding length and other parameters
36 #include "gnunet_common.h"
37 #include "gnunet_util_lib.h"
39 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS || 1
41 #define CURVE "NIST P-521"
43 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
45 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
47 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
50 * Log an error message at log-level 'level' that indicates
51 * a failure of the command 'cmd' with the message given
52 * by gcry_strerror(rc).
54 #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);
58 * The private information of an ECC private key.
60 struct GNUNET_CRYPTO_EccPrivateKey
64 * Libgcrypt S-expression for the ECC key.
71 * If target != size, move target bytes to the
72 * end of the size-sized buffer and zero out the
73 * first target-size bytes.
75 * @param buf original buffer
76 * @param size number of bytes in the buffer
77 * @param target target size of the buffer
80 adjust (unsigned char *buf, size_t size, size_t target)
84 memmove (&buf[target - size], buf, size);
85 memset (buf, 0, target - size);
91 * Free memory occupied by ECC key
93 * @param privatekey pointer to the memory to free
96 GNUNET_CRYPTO_ecc_key_free (struct GNUNET_CRYPTO_EccPrivateKey *privatekey)
98 gcry_sexp_release (privatekey->sexp);
99 GNUNET_free (privatekey);
104 * Extract values from an S-expression.
106 * @param array where to store the result(s)
107 * @param sexp S-expression to parse
108 * @param topname top-level name in the S-expression that is of interest
109 * @param elems names of the elements to extract
110 * @return 0 on success
113 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
122 list = gcry_sexp_find_token (sexp, topname, 0);
125 l2 = gcry_sexp_cadr (list);
126 gcry_sexp_release (list);
132 for (s = elems; *s; s++, idx++)
134 l2 = gcry_sexp_find_token (list, s, 1);
137 for (i = 0; i < idx; i++)
139 gcry_free (array[i]);
142 gcry_sexp_release (list);
143 return 3; /* required parameter not found */
145 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
146 gcry_sexp_release (l2);
149 for (i = 0; i < idx; i++)
151 gcry_free (array[i]);
154 gcry_sexp_release (list);
155 return 4; /* required parameter is invalid */
158 gcry_sexp_release (list);
164 * Extract the public key for the given private key.
166 * @param priv the private key
167 * @param pub where to write the public key
170 GNUNET_CRYPTO_ecc_key_get_public (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
171 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
177 rc = key_from_sexp (&skey, priv->sexp, "public-key", "q");
179 rc = key_from_sexp (&skey, priv->sexp, "private-key", "q");
181 rc = key_from_sexp (&skey, priv->sexp, "ecc", "q");
182 GNUNET_assert (0 == rc);
183 pub->size = htons (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
184 size = GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH;
186 gcry_mpi_print (GCRYMPI_FMT_USG, pub->key, size, &size,
188 pub->len = htons (size);
189 adjust (&pub->key[0], size, GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH);
190 gcry_mpi_release (skey);
195 * Convert a public key to a string.
197 * @param pub key to convert
198 * @return string representing 'pub'
201 GNUNET_CRYPTO_ecc_public_key_to_string (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
204 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
208 keylen += 5 - keylen % 5;
210 pubkeybuf = GNUNET_malloc (keylen + 1);
211 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
212 sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded),
217 GNUNET_free (pubkeybuf);
226 * Convert a string representing a public key to a public key.
228 * @param enc encoded public key
229 * @param enclen number of bytes in enc (without 0-terminator)
230 * @param pub where to store the public key
231 * @return GNUNET_OK on success
234 GNUNET_CRYPTO_ecc_public_key_from_string (const char *enc,
236 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
238 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
241 keylen += 5 - keylen % 5;
243 if (enclen != keylen)
244 return GNUNET_SYSERR;
246 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
247 (unsigned char*) pub,
248 sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)))
249 return GNUNET_SYSERR;
250 if ( (ntohs (pub->size) != sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) ||
251 (ntohs (pub->len) > GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH) )
252 return GNUNET_SYSERR;
258 * Convert the given public key from the network format to the
259 * S-expression that can be used by libgcrypt.
261 * @param publicKey public key to decode
262 * @return NULL on error
265 decode_public_key (const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *publicKey)
273 if (ntohs (publicKey->len) > GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH)
278 size = ntohs (publicKey->size);
279 if (0 != (rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG, publicKey->key, size, &size)))
281 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
284 rc = gcry_sexp_build (&result, &erroff, "(public-key(ecc((curve \"" CURVE "\")(q %m)))", q);
285 gcry_mpi_release (q);
288 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
296 * Encode the private key in a format suitable for
297 * storing it into a file.
299 * @param key key to encode
300 * @return encoding of the private key.
301 * The first 4 bytes give the size of the array, as usual.
303 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
304 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key)
306 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *retval;
312 if (0 != gcry_pk_testkey (key->sexp))
318 size = gcry_sexp_sprint (key->sexp,
319 GCRYSEXP_FMT_DEFAULT,
320 &buf[2], sizeof (buf) - sizeof (uint16_t));
326 GNUNET_assert (size < 65536 - sizeof (uint16_t));
327 be = htons ((uint16_t) size + (sizeof (be)));
328 memcpy (buf, &be, sizeof (be));
330 retval = GNUNET_malloc (size);
331 memcpy (retval, buf, size);
337 * Decode the private key from the file-format back
338 * to the "normal", internal format.
340 * @param buf the buffer where the private key data is stored
341 * @param len the length of the data in 'buffer'
342 * @return NULL on error
344 struct GNUNET_CRYPTO_EccPrivateKey *
345 GNUNET_CRYPTO_ecc_decode_key (const char *buf,
348 struct GNUNET_CRYPTO_EccPrivateKey *ret;
354 if (len < sizeof (uint16_t))
356 memcpy (&be, buf, sizeof (be));
357 if (len != ntohs (be))
359 if (0 != (rc = gcry_sexp_sscan (&sexp,
362 len - sizeof (uint16_t))))
364 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
367 if (0 != (rc = gcry_pk_testkey (sexp)))
369 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
372 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
379 * Create a new private key. Caller must free return value.
381 * @return fresh private key
383 static struct GNUNET_CRYPTO_EccPrivateKey *
386 struct GNUNET_CRYPTO_EccPrivateKey *ret;
388 gcry_sexp_t s_keyparam;
391 gcry_sexp_build (&s_keyparam, NULL,
392 "(genkey(ecc(curve \"" CURVE "\")))"));
393 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
394 gcry_sexp_release (s_keyparam);
396 GNUNET_assert (0 == gcry_pk_testkey (s_key));
398 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
405 * Try to read the private key from the given file.
407 * @param filename file to read the key from
408 * @return NULL on error
410 static struct GNUNET_CRYPTO_EccPrivateKey *
411 try_read_key (const char *filename)
413 struct GNUNET_CRYPTO_EccPrivateKey *ret;
414 struct GNUNET_DISK_FileHandle *fd;
417 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
420 /* hostkey file exists already, read it! */
421 if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
422 GNUNET_DISK_PERM_NONE)))
424 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
427 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
429 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
430 (void) GNUNET_DISK_file_close (fd);
435 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
440 LOG (GNUNET_ERROR_TYPE_ERROR,
441 _("File `%s' does not contain a valid private key (too long, %llu bytes). Deleting it.\n"),
443 (unsigned long long) fs);
444 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
445 if (0 != UNLINK (filename))
446 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
452 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
453 if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs)))
455 LOG (GNUNET_ERROR_TYPE_ERROR,
456 _("File `%s' does not contain a valid private key (failed decode, %llu bytes). Deleting it.\n"),
458 (unsigned long long) fs);
459 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
460 if (0 != UNLINK (filename))
461 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
465 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
471 * Wait for a short time (we're trying to lock a file or want
472 * to give another process a shot at finishing a disk write, etc.).
473 * Sleeps for 100ms (as that should be long enough for virtually all
474 * modern systems to context switch and allow another process to do
480 struct GNUNET_TIME_Relative timeout;
482 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
483 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
488 * Create a new private key by reading it from a file. If the
489 * files does not exist, create a new key and write it to the
490 * file. Caller must free return value. Note that this function
491 * can not guarantee that another process might not be trying
492 * the same operation on the same file at the same time.
493 * If the contents of the file
494 * are invalid the old file is deleted and a fresh key is
497 * @return new private key, NULL on error (for example,
500 struct GNUNET_CRYPTO_EccPrivateKey *
501 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
503 struct GNUNET_CRYPTO_EccPrivateKey *ret;
504 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
506 struct GNUNET_DISK_FileHandle *fd;
510 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
511 struct GNUNET_PeerIdentity pid;
513 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
515 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
517 fd = GNUNET_DISK_file_open (filename,
518 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
519 | GNUNET_DISK_OPEN_FAILIFEXISTS,
520 GNUNET_DISK_PERM_USER_READ |
521 GNUNET_DISK_PERM_USER_WRITE);
526 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
528 /* must exist but not be accessible, fail for good! */
529 if (0 != ACCESS (filename, R_OK))
530 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
532 GNUNET_break (0); /* what is going on!? */
537 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
543 GNUNET_DISK_file_lock (fd, 0,
544 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
551 LOG (GNUNET_ERROR_TYPE_ERROR,
552 _("Could not acquire lock on file `%s': %s...\n"), filename,
556 LOG (GNUNET_ERROR_TYPE_INFO,
557 _("Creating a new private key. This may take a while.\n"));
558 ret = ecc_key_create ();
559 GNUNET_assert (ret != NULL);
560 enc = GNUNET_CRYPTO_ecc_encode_key (ret);
561 GNUNET_assert (enc != NULL);
562 GNUNET_assert (ntohs (enc->size) ==
563 GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
566 GNUNET_DISK_file_sync (fd);
568 GNUNET_DISK_file_unlock (fd, 0,
569 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
570 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
571 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
572 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
573 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
574 LOG (GNUNET_ERROR_TYPE_INFO,
575 _("I am host `%s'. Stored new private key in `%s'.\n"),
576 GNUNET_i2s (&pid), filename);
579 /* hostkey file exists already, read it! */
580 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
581 GNUNET_DISK_PERM_NONE);
584 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
591 GNUNET_DISK_file_lock (fd, 0,
592 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
598 LOG (GNUNET_ERROR_TYPE_ERROR,
599 _("Could not acquire lock on file `%s': %s...\n"), filename,
601 LOG (GNUNET_ERROR_TYPE_ERROR,
603 ("This may be ok if someone is currently generating a hostkey.\n"));
608 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
610 /* eh, what!? File we opened is now gone!? */
611 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
613 GNUNET_DISK_file_unlock (fd, 0,
614 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
615 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
616 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
620 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
622 if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
624 /* maybe we got the read lock before the hostkey generating
625 * process had a chance to get the write lock; give it up! */
627 GNUNET_DISK_file_unlock (fd, 0,
628 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
629 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
632 LOG (GNUNET_ERROR_TYPE_ERROR,
634 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
635 filename, (unsigned int) fs,
636 (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
637 LOG (GNUNET_ERROR_TYPE_ERROR,
639 ("This may be ok if someone is currently generating a hostkey.\n"));
641 short_wait (); /* wait a bit longer! */
646 enc = GNUNET_malloc (fs);
647 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
648 len = ntohs (enc->size);
651 (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len))))
653 LOG (GNUNET_ERROR_TYPE_ERROR,
654 _("File `%s' does not contain a valid private key. Deleting it.\n"),
656 if (0 != UNLINK (filename))
658 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
663 GNUNET_DISK_file_unlock (fd, 0,
664 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
665 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
666 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
669 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
670 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
671 LOG (GNUNET_ERROR_TYPE_INFO,
672 _("I am host `%s'. Read private key from `%s'.\n"), GNUNET_i2s (&pid),
680 * Handle to cancel private key generation and state for the
681 * key generation operation.
683 struct GNUNET_CRYPTO_EccKeyGenerationContext
687 * Continuation to call upon completion.
689 GNUNET_CRYPTO_EccKeyCallback cont;
692 * Closure for 'cont'.
702 * Handle to the helper process which does the key generation.
704 struct GNUNET_OS_Process *gnunet_ecc;
707 * Handle to 'stdout' of gnunet-ecc. We 'read' on stdout to detect
708 * process termination (instead of messing with SIGCHLD).
710 struct GNUNET_DISK_PipeHandle *gnunet_ecc_out;
713 * Location where we store the private key if it already existed.
714 * (if this is used, 'filename', 'gnunet_ecc' and 'gnunet_ecc_out' will
717 struct GNUNET_CRYPTO_EccPrivateKey *pk;
720 * Task reading from 'gnunet_ecc_out' to wait for process termination.
722 GNUNET_SCHEDULER_TaskIdentifier read_task;
728 * Abort ECC key generation.
730 * @param gc key generation context to abort
733 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc)
735 if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
737 GNUNET_SCHEDULER_cancel (gc->read_task);
738 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
740 if (NULL != gc->gnunet_ecc)
742 (void) GNUNET_OS_process_kill (gc->gnunet_ecc, SIGKILL);
743 GNUNET_break (GNUNET_OK ==
744 GNUNET_OS_process_wait (gc->gnunet_ecc));
745 GNUNET_OS_process_destroy (gc->gnunet_ecc);
746 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
749 if (NULL != gc->filename)
751 if (0 != UNLINK (gc->filename))
752 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
753 GNUNET_free (gc->filename);
756 GNUNET_CRYPTO_ecc_key_free (gc->pk);
762 * Task called upon shutdown or process termination of 'gnunet-ecc' during
763 * ECC key generation. Check where we are and perform the appropriate
766 * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
767 * @param tc scheduler context
770 check_key_generation_completion (void *cls,
771 const struct GNUNET_SCHEDULER_TaskContext *tc)
773 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
774 struct GNUNET_CRYPTO_EccPrivateKey *pk;
776 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
777 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
779 gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
780 GNUNET_CRYPTO_ecc_key_create_stop (gc);
783 GNUNET_assert (GNUNET_OK ==
784 GNUNET_OS_process_wait (gc->gnunet_ecc));
785 GNUNET_OS_process_destroy (gc->gnunet_ecc);
786 gc->gnunet_ecc = NULL;
787 if (NULL == (pk = try_read_key (gc->filename)))
790 gc->cont (gc->cont_cls, NULL, _("gnunet-ecc failed"));
791 GNUNET_CRYPTO_ecc_key_create_stop (gc);
794 gc->cont (gc->cont_cls, pk, NULL);
795 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
796 GNUNET_free (gc->filename);
802 * Return the private ECC key which already existed on disk
803 * (asynchronously) to the caller.
805 * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
806 * @param tc scheduler context (unused)
809 async_return_key (void *cls,
810 const struct GNUNET_SCHEDULER_TaskContext *tc)
812 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
814 gc->cont (gc->cont_cls,
822 * Create a new private key by reading it from a file. If the files
823 * does not exist, create a new key and write it to the file. If the
824 * contents of the file are invalid the old file is deleted and a
825 * fresh key is created.
827 * @param filename name of file to use for storage
828 * @param cont function to call when done (or on errors)
829 * @param cont_cls closure for 'cont'
830 * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
832 struct GNUNET_CRYPTO_EccKeyGenerationContext *
833 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
834 GNUNET_CRYPTO_EccKeyCallback cont,
837 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc;
838 struct GNUNET_CRYPTO_EccPrivateKey *pk;
839 const char *weak_random;
841 if (NULL != (pk = try_read_key (filename)))
843 /* quick happy ending: key already exists! */
844 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
847 gc->cont_cls = cont_cls;
848 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
852 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
853 gc->filename = GNUNET_strdup (filename);
855 gc->cont_cls = cont_cls;
856 gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
860 if (NULL == gc->gnunet_ecc_out)
862 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
863 GNUNET_free (gc->filename);
869 GNUNET_CRYPTO_random_is_weak ())
871 gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
872 GNUNET_OS_INHERIT_STD_ERR,
880 if (NULL == gc->gnunet_ecc)
882 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
883 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
884 GNUNET_free (gc->filename);
888 GNUNET_assert (GNUNET_OK ==
889 GNUNET_DISK_pipe_close_end (gc->gnunet_ecc_out,
890 GNUNET_DISK_PIPE_END_WRITE));
891 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
892 GNUNET_DISK_pipe_handle (gc->gnunet_ecc_out,
893 GNUNET_DISK_PIPE_END_READ),
894 &check_key_generation_completion,
901 * Setup a hostkey file for a peer given the name of the
902 * configuration file (!). This function is used so that
903 * at a later point code can be certain that reading a
904 * hostkey is fast (for example in time-dependent testcases).
906 * @param cfg_name name of the configuration file to use
909 GNUNET_CRYPTO_ecc_setup_hostkey (const char *cfg_name)
911 struct GNUNET_CONFIGURATION_Handle *cfg;
912 struct GNUNET_CRYPTO_EccPrivateKey *pk;
915 cfg = GNUNET_CONFIGURATION_create ();
916 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
918 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
920 pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
922 GNUNET_CRYPTO_ecc_key_free (pk);
925 GNUNET_CONFIGURATION_destroy (cfg);
930 * Encrypt a block with the public key of another host that uses the
933 * @param block the block to encrypt
934 * @param size the size of block
935 * @param publicKey the encoded public key used to encrypt
936 * @param target where to store the encrypted block
937 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
940 GNUNET_CRYPTO_ecc_encrypt (const void *block, size_t size,
941 const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
943 struct GNUNET_CRYPTO_EccEncryptedData *target)
952 GNUNET_assert (size <= sizeof (struct GNUNET_HashCode));
953 if (! (psexp = decode_public_key (publicKey)))
954 return GNUNET_SYSERR;
957 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
959 gcry_sexp_build (&data, &erroff,
960 "(data (flags pkcs1)(value %m))", val));
961 gcry_mpi_release (val);
962 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, psexp));
963 gcry_sexp_release (data);
964 gcry_sexp_release (psexp);
965 isize = gcry_sexp_sprint (result,
966 GCRYSEXP_FMT_DEFAULT,
968 GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH);
972 return GNUNET_SYSERR;
974 target->size = htons ((uint16_t) (isize + sizeof (uint16_t)));
975 /* padd with zeros */
976 memset (&target->encoding[isize], 0, GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH - isize);
982 * Decrypt a given block with the hostkey.
984 * @param key the key with which to decrypt this block
985 * @param block the data to decrypt, encoded as returned by encrypt
986 * @param result pointer to a location where the result can be stored
987 * @param max the maximum number of bits to store for the result, if
988 * the decrypted block is bigger, an error is returned
989 * @return the size of the decrypted block, -1 on error
992 GNUNET_CRYPTO_ecc_decrypt (const struct GNUNET_CRYPTO_EccPrivateKey *key,
993 const struct GNUNET_CRYPTO_EccEncryptedData *block,
994 void *result, size_t max)
996 gcry_sexp_t resultsexp;
1001 unsigned char *endp;
1004 GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
1006 size = ntohs (block->size);
1007 if (size < sizeof (uint16_t))
1010 gcry_sexp_sscan (&data,
1012 block->encoding, size - sizeof (uint16_t)));
1013 GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
1014 gcry_sexp_release (data);
1015 /* resultsexp has format "(value %m)" */
1016 GNUNET_assert (NULL !=
1017 (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
1018 gcry_sexp_release (resultsexp);
1019 size = max + GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH * 2;
1021 unsigned char tmp[size];
1023 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
1024 gcry_mpi_release (val);
1026 endp += (size - max);
1028 memcpy (result, endp, size);
1035 * Convert the data specified in the given purpose argument to an
1036 * S-expression suitable for signature operations.
1038 * @param purpose data to convert
1039 * @return converted s-expression
1042 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
1044 struct GNUNET_HashCode hc;
1048 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1049 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
1050 bufSize = strlen (FORMATSTRING) + 1;
1054 memcpy (buff, FORMATSTRING, bufSize);
1058 ("0123456789012345678901234567890123456789012345678901234567890123))")
1059 - 1], &hc, sizeof (struct GNUNET_HashCode));
1060 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1068 * Sign a given block.
1070 * @param key private key to use for the signing
1071 * @param purpose what to sign (size, purpose)
1072 * @param sig where to write the signature
1073 * @return GNUNET_SYSERR on error, GNUNET_OK on success
1076 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1077 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1078 struct GNUNET_CRYPTO_EccSignature *sig)
1084 data = data_to_pkcs1 (purpose);
1085 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
1086 gcry_sexp_release (data);
1087 ssize = gcry_sexp_sprint (result,
1088 GCRYSEXP_FMT_DEFAULT,
1090 GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH);
1094 return GNUNET_SYSERR;
1096 sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
1097 /* padd with zeros */
1098 memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH - ssize);
1099 gcry_sexp_release (result);
1107 * @param purpose what is the purpose that the signature should have?
1108 * @param validate block to validate (size, purpose, data)
1109 * @param sig signature that is being validated
1110 * @param publicKey public key of the signer
1111 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1114 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1115 const struct GNUNET_CRYPTO_EccSignaturePurpose
1117 const struct GNUNET_CRYPTO_EccSignature *sig,
1118 const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1122 gcry_sexp_t sigdata;
1128 if (purpose != ntohl (validate->purpose))
1129 return GNUNET_SYSERR; /* purpose mismatch */
1130 size = ntohs (sig->size);
1131 if ( (size < sizeof (uint16_t)) ||
1132 (size > GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1133 return GNUNET_SYSERR; /* size out of range */
1134 data = data_to_pkcs1 (validate);
1136 gcry_sexp_sscan (&sigdata, &erroff,
1137 sig->sexpr, size - sizeof (uint16_t)));
1138 if (! (psexp = decode_public_key (publicKey)))
1140 gcry_sexp_release (data);
1141 gcry_sexp_release (sigdata);
1142 return GNUNET_SYSERR;
1144 rc = gcry_pk_verify (sigdata, data, psexp);
1145 gcry_sexp_release (psexp);
1146 gcry_sexp_release (data);
1147 gcry_sexp_release (sigdata);
1150 LOG (GNUNET_ERROR_TYPE_WARNING,
1151 _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1152 __LINE__, gcry_strerror (rc));
1153 return GNUNET_SYSERR;
1159 /* end of crypto_ecc.c */