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
28 #include "gnunet_common.h"
29 #include "gnunet_util_lib.h"
31 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
33 #define CURVE "NIST P-256"
35 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
37 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
39 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
42 * Log an error message at log-level 'level' that indicates
43 * a failure of the command 'cmd' with the message given
44 * by gcry_strerror(rc).
46 #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);
50 * The private information of an ECC private key.
52 struct GNUNET_CRYPTO_EccPrivateKey
56 * Libgcrypt S-expression for the ECC key.
63 * Free memory occupied by ECC key
65 * @param privatekey pointer to the memory to free
68 GNUNET_CRYPTO_ecc_key_free (struct GNUNET_CRYPTO_EccPrivateKey *privatekey)
70 gcry_sexp_release (privatekey->sexp);
71 GNUNET_free (privatekey);
76 * Extract values from an S-expression.
78 * @param array where to store the result(s)
79 * @param sexp S-expression to parse
80 * @param topname top-level name in the S-expression that is of interest
81 * @param elems names of the elements to extract
82 * @return 0 on success
85 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
94 list = gcry_sexp_find_token (sexp, topname, 0);
97 l2 = gcry_sexp_cadr (list);
98 gcry_sexp_release (list);
104 for (s = elems; *s; s++, idx++)
106 l2 = gcry_sexp_find_token (list, s, 1);
109 for (i = 0; i < idx; i++)
111 gcry_free (array[i]);
114 gcry_sexp_release (list);
115 return 3; /* required parameter not found */
117 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
118 gcry_sexp_release (l2);
121 for (i = 0; i < idx; i++)
123 gcry_free (array[i]);
126 gcry_sexp_release (list);
127 return 4; /* required parameter is invalid */
130 gcry_sexp_release (list);
136 * Extract the public key for the given private key.
138 * @param priv the private key
139 * @param pub where to write the public key
142 GNUNET_CRYPTO_ecc_key_get_public (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
143 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
149 memset (pub, 0, sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
150 rc = key_from_sexp (&skey, priv->sexp, "public-key", "q");
152 rc = key_from_sexp (&skey, priv->sexp, "private-key", "q");
154 rc = key_from_sexp (&skey, priv->sexp, "ecc", "q");
155 GNUNET_assert (0 == rc);
156 pub->size = htons (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
157 size = GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH;
159 gcry_mpi_print (GCRYMPI_FMT_USG, pub->key, size, &size,
161 pub->len = htons (size);
162 gcry_mpi_release (skey);
167 * Convert a public key to a string.
169 * @param pub key to convert
170 * @return string representing 'pub'
173 GNUNET_CRYPTO_ecc_public_key_to_string (const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
176 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
180 keylen += 5 - keylen % 5;
182 pubkeybuf = GNUNET_malloc (keylen + 1);
183 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
184 sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded),
189 GNUNET_free (pubkeybuf);
198 * Convert a string representing a public key to a public key.
200 * @param enc encoded public key
201 * @param enclen number of bytes in enc (without 0-terminator)
202 * @param pub where to store the public key
203 * @return GNUNET_OK on success
206 GNUNET_CRYPTO_ecc_public_key_from_string (const char *enc,
208 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
210 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
213 keylen += 5 - keylen % 5;
215 if (enclen != keylen)
216 return GNUNET_SYSERR;
218 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
219 (unsigned char*) pub,
220 sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)))
221 return GNUNET_SYSERR;
222 if ( (ntohs (pub->size) != sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) ||
223 (ntohs (pub->len) > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH) )
224 return GNUNET_SYSERR;
230 * Convert the given public key from the network format to the
231 * S-expression that can be used by libgcrypt.
233 * @param publicKey public key to decode
234 * @return NULL on error
237 decode_public_key (const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *publicKey)
245 if (ntohs (publicKey->len) > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH)
250 size = ntohs (publicKey->len);
251 if (0 != (rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG, publicKey->key, size, &size)))
253 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
257 rc = gcry_sexp_build (&result, &erroff,
258 "(public-key(ecdsa(curve \"" CURVE "\")(q %m)))",
260 gcry_mpi_release (q);
263 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
266 // FIXME: is this key expected to pass pk_testkey?
269 if (0 != (rc = gcry_pk_testkey (result)))
271 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
272 gcry_sexp_release (result);
282 * Encode the private key in a format suitable for
283 * storing it into a file.
285 * @param key key to encode
286 * @return encoding of the private key.
287 * The first 4 bytes give the size of the array, as usual.
289 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
290 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key)
292 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *retval;
298 if (0 != gcry_pk_testkey (key->sexp))
304 size = gcry_sexp_sprint (key->sexp,
305 GCRYSEXP_FMT_DEFAULT,
306 &buf[2], sizeof (buf) - sizeof (uint16_t));
312 GNUNET_assert (size < 65536 - sizeof (uint16_t));
313 be = htons ((uint16_t) size + (sizeof (be)));
314 memcpy (buf, &be, sizeof (be));
316 retval = GNUNET_malloc (size);
317 memcpy (retval, buf, size);
323 * Decode the private key from the file-format back
324 * to the "normal", internal format.
326 * @param buf the buffer where the private key data is stored
327 * @param len the length of the data in 'buffer'
328 * @param validate GNUNET_YES to validate that the key is well-formed,
329 * GNUNET_NO if the key comes from a totally trusted source
330 * and validation is considered too expensive
331 * @return NULL on error
333 struct GNUNET_CRYPTO_EccPrivateKey *
334 GNUNET_CRYPTO_ecc_decode_key (const char *buf,
338 struct GNUNET_CRYPTO_EccPrivateKey *ret;
344 if (len < sizeof (uint16_t))
346 memcpy (&be, buf, sizeof (be));
347 if (len < ntohs (be))
350 if (0 != (rc = gcry_sexp_sscan (&sexp,
353 len - sizeof (uint16_t))))
355 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
358 if ( (GNUNET_YES == validate) &&
359 (0 != (rc = gcry_pk_testkey (sexp))) )
361 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
364 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
371 * Create a new private key. Caller must free return value.
373 * @return fresh private key
375 struct GNUNET_CRYPTO_EccPrivateKey *
376 GNUNET_CRYPTO_ecc_key_create ()
378 struct GNUNET_CRYPTO_EccPrivateKey *ret;
380 gcry_sexp_t s_keyparam;
383 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
384 "(genkey(ecdsa(curve \"" CURVE "\")))")))
386 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
389 if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
391 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
392 gcry_sexp_release (s_keyparam);
395 gcry_sexp_release (s_keyparam);
397 if (0 != (rc = gcry_pk_testkey (s_key)))
399 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
400 gcry_sexp_release (s_key);
404 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
411 * Try to read the private key from the given file.
413 * @param filename file to read the key from
414 * @return NULL on error
416 static struct GNUNET_CRYPTO_EccPrivateKey *
417 try_read_key (const char *filename)
419 struct GNUNET_CRYPTO_EccPrivateKey *ret;
420 struct GNUNET_DISK_FileHandle *fd;
423 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
426 /* key file exists already, read it! */
427 if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
428 GNUNET_DISK_PERM_NONE)))
430 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
433 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
435 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
436 (void) GNUNET_DISK_file_close (fd);
441 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
446 LOG (GNUNET_ERROR_TYPE_ERROR,
447 _("File `%s' does not contain a valid private key (too long, %llu bytes). Deleting it.\n"),
449 (unsigned long long) fs);
450 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
451 if (0 != UNLINK (filename))
452 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
458 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
459 if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs, GNUNET_YES)))
461 LOG (GNUNET_ERROR_TYPE_ERROR,
462 _("File `%s' does not contain a valid private key (failed decode, %llu bytes). Deleting it.\n"),
464 (unsigned long long) fs);
465 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
466 if (0 != UNLINK (filename))
467 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
471 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
477 * Wait for a short time (we're trying to lock a file or want
478 * to give another process a shot at finishing a disk write, etc.).
479 * Sleeps for 100ms (as that should be long enough for virtually all
480 * modern systems to context switch and allow another process to do
486 struct GNUNET_TIME_Relative timeout;
488 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
489 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
494 * Create a new private key by reading it from a file. If the
495 * files does not exist, create a new key and write it to the
496 * file. Caller must free return value. Note that this function
497 * can not guarantee that another process might not be trying
498 * the same operation on the same file at the same time.
499 * If the contents of the file
500 * are invalid the old file is deleted and a fresh key is
503 * @return new private key, NULL on error (for example,
506 struct GNUNET_CRYPTO_EccPrivateKey *
507 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
509 struct GNUNET_CRYPTO_EccPrivateKey *ret;
510 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
512 struct GNUNET_DISK_FileHandle *fd;
516 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
517 struct GNUNET_PeerIdentity pid;
519 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
521 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
523 fd = GNUNET_DISK_file_open (filename,
524 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
525 | GNUNET_DISK_OPEN_FAILIFEXISTS,
526 GNUNET_DISK_PERM_USER_READ |
527 GNUNET_DISK_PERM_USER_WRITE);
532 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
534 /* must exist but not be accessible, fail for good! */
535 if (0 != ACCESS (filename, R_OK))
536 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
538 GNUNET_break (0); /* what is going on!? */
543 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
549 GNUNET_DISK_file_lock (fd, 0,
550 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
557 LOG (GNUNET_ERROR_TYPE_ERROR,
558 _("Could not acquire lock on file `%s': %s...\n"), filename,
562 LOG (GNUNET_ERROR_TYPE_INFO,
563 _("Creating a new private key. This may take a while.\n"));
564 ret = GNUNET_CRYPTO_ecc_key_create ();
565 GNUNET_assert (ret != NULL);
566 enc = GNUNET_CRYPTO_ecc_encode_key (ret);
567 GNUNET_assert (enc != NULL);
568 GNUNET_assert (ntohs (enc->size) ==
569 GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
572 GNUNET_DISK_file_sync (fd);
574 GNUNET_DISK_file_unlock (fd, 0,
575 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
576 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
577 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
578 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
579 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
582 /* key file exists already, read it! */
583 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
584 GNUNET_DISK_PERM_NONE);
587 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
594 GNUNET_DISK_file_lock (fd, 0,
595 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
601 LOG (GNUNET_ERROR_TYPE_ERROR,
602 _("Could not acquire lock on file `%s': %s...\n"), filename,
604 LOG (GNUNET_ERROR_TYPE_ERROR,
606 ("This may be ok if someone is currently generating a private key.\n"));
611 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
613 /* eh, what!? File we opened is now gone!? */
614 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
616 GNUNET_DISK_file_unlock (fd, 0,
617 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
618 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
619 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
623 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
625 if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
627 /* maybe we got the read lock before the key generating
628 * process had a chance to get the write lock; give it up! */
630 GNUNET_DISK_file_unlock (fd, 0,
631 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
632 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
635 LOG (GNUNET_ERROR_TYPE_ERROR,
637 ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
638 filename, (unsigned int) fs,
639 (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
640 LOG (GNUNET_ERROR_TYPE_ERROR,
642 ("This may be ok if someone is currently generating a key.\n"));
644 short_wait (); /* wait a bit longer! */
649 enc = GNUNET_malloc (fs);
650 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
651 len = ntohs (enc->size);
654 (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len, GNUNET_YES))))
656 LOG (GNUNET_ERROR_TYPE_ERROR,
657 _("File `%s' does not contain a valid private key. Deleting it.\n"),
659 if (0 != UNLINK (filename))
661 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
666 GNUNET_DISK_file_unlock (fd, 0,
667 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
668 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
669 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
672 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
673 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
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;
840 if (NULL != (pk = try_read_key (filename)))
842 /* quick happy ending: key already exists! */
843 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
846 gc->cont_cls = cont_cls;
847 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
851 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
852 gc->filename = GNUNET_strdup (filename);
854 gc->cont_cls = cont_cls;
855 gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
859 if (NULL == gc->gnunet_ecc_out)
861 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
862 GNUNET_free (gc->filename);
866 gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
867 GNUNET_OS_INHERIT_STD_ERR,
874 if (NULL == gc->gnunet_ecc)
876 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
877 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
878 GNUNET_free (gc->filename);
882 GNUNET_assert (GNUNET_OK ==
883 GNUNET_DISK_pipe_close_end (gc->gnunet_ecc_out,
884 GNUNET_DISK_PIPE_END_WRITE));
885 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
886 GNUNET_DISK_pipe_handle (gc->gnunet_ecc_out,
887 GNUNET_DISK_PIPE_END_READ),
888 &check_key_generation_completion,
895 * Setup a key file for a peer given the name of the
896 * configuration file (!). This function is used so that
897 * at a later point code can be certain that reading a
898 * key is fast (for example in time-dependent testcases).
900 * @param cfg_name name of the configuration file to use
903 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
905 struct GNUNET_CONFIGURATION_Handle *cfg;
906 struct GNUNET_CRYPTO_EccPrivateKey *pk;
909 cfg = GNUNET_CONFIGURATION_create ();
910 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
912 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
914 pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
916 GNUNET_CRYPTO_ecc_key_free (pk);
919 GNUNET_CONFIGURATION_destroy (cfg);
924 * Convert the data specified in the given purpose argument to an
925 * S-expression suitable for signature operations.
927 * @param purpose data to convert
928 * @return converted s-expression
931 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
933 struct GNUNET_CRYPTO_ShortHashCode hc;
937 GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
938 #define FORMATSTRING "(4:data(5:flags3:raw)(5:value32:01234567890123456789012345678901))"
939 bufSize = strlen (FORMATSTRING) + 1;
943 memcpy (buff, FORMATSTRING, bufSize);
947 ("01234567890123456789012345678901))")
948 - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
949 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
957 * Sign a given block.
959 * @param key private key to use for the signing
960 * @param purpose what to sign (size, purpose)
961 * @param sig where to write the signature
962 * @return GNUNET_SYSERR on error, GNUNET_OK on success
965 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
966 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
967 struct GNUNET_CRYPTO_EccSignature *sig)
974 data = data_to_pkcs1 (purpose);
975 if (0 != (rc = gcry_pk_sign (&result, data, key->sexp)))
977 LOG (GNUNET_ERROR_TYPE_WARNING,
978 _("ECC signing failed at %s:%d: %s\n"), __FILE__,
979 __LINE__, gcry_strerror (rc));
980 gcry_sexp_release (data);
981 return GNUNET_SYSERR;
983 gcry_sexp_release (data);
984 ssize = gcry_sexp_sprint (result,
985 GCRYSEXP_FMT_DEFAULT,
987 GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH);
991 return GNUNET_SYSERR;
993 sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
994 /* padd with zeros */
995 memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - ssize);
996 gcry_sexp_release (result);
1004 * @param purpose what is the purpose that the signature should have?
1005 * @param validate block to validate (size, purpose, data)
1006 * @param sig signature that is being validated
1007 * @param publicKey public key of the signer
1008 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1011 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1012 const struct GNUNET_CRYPTO_EccSignaturePurpose
1014 const struct GNUNET_CRYPTO_EccSignature *sig,
1015 const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1019 gcry_sexp_t sigdata;
1025 if (purpose != ntohl (validate->purpose))
1026 return GNUNET_SYSERR; /* purpose mismatch */
1027 size = ntohs (sig->size);
1028 if ( (size < sizeof (uint16_t)) ||
1029 (size > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1030 return GNUNET_SYSERR; /* size out of range */
1031 data = data_to_pkcs1 (validate);
1033 gcry_sexp_sscan (&sigdata, &erroff,
1034 sig->sexpr, size - sizeof (uint16_t)));
1035 if (! (psexp = decode_public_key (publicKey)))
1037 gcry_sexp_release (data);
1038 gcry_sexp_release (sigdata);
1039 return GNUNET_SYSERR;
1041 rc = gcry_pk_verify (sigdata, data, psexp);
1042 gcry_sexp_release (psexp);
1043 gcry_sexp_release (data);
1044 gcry_sexp_release (sigdata);
1047 LOG (GNUNET_ERROR_TYPE_WARNING,
1048 _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1049 __LINE__, gcry_strerror (rc));
1050 return GNUNET_SYSERR;
1057 * Derive key material from a public and a private ECC key.
1059 * @param key private key to use for the ECDH (x)
1060 * @param pub public key to use for the ECDY (yG)
1061 * @param key_material where to write the key material (xyG)
1062 * @return GNUNET_SYSERR on error, GNUNET_OK on success
1065 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1066 const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub,
1067 struct GNUNET_HashCode *key_material)
1073 unsigned char sdata_buf[2048]; /* big enough to print 'sdata' and 'r_sig' */
1075 /* first, extract the q value from the public key */
1080 if (! (psexp = decode_public_key (pub)))
1081 return GNUNET_SYSERR;
1082 rc = key_from_sexp (&sdata, psexp, "public-key", "q");
1084 rc = key_from_sexp (&sdata, psexp, "ecc", "q");
1085 GNUNET_assert (0 == rc);
1086 gcry_sexp_release (psexp);
1087 size = sizeof (sdata_buf);
1089 gcry_mpi_print (GCRYMPI_FMT_USG, sdata_buf, size, &size,
1091 gcry_mpi_release (sdata);
1093 /* convert q value into an S-expression -- whatever format libgcrypt wants,
1094 re-using format from sign operation for now... */
1098 #define FORMATPREFIX "(4:data(5:flags3:raw)(5:value%u:"
1099 #define FORMATPOSTFIX "))"
1100 sexp_string = GNUNET_malloc (strlen (FORMATPREFIX) + size + 12 +
1101 strlen (FORMATPOSTFIX) + 1);
1102 GNUNET_snprintf (sexp_string,
1103 strlen (FORMATPREFIX) + 12,
1106 slen = strlen (sexp_string);
1107 memcpy (&sexp_string[slen],
1110 memcpy (&sexp_string[slen + size],
1112 strlen (FORMATPOSTFIX) + 1);
1113 GNUNET_assert (0 == gcry_sexp_new (&data,
1115 slen + size + strlen (FORMATPOSTFIX),
1117 GNUNET_free (sexp_string);
1119 /* then call the 'multiply' function, hoping it simply multiplies the points;
1120 here we need essentially a WRAPPER around _gcry_mpi_ex_mul_point! - FIXME-WK!*/
1125 rc = gcry_ecc_mul_point (&result, data /* scalar */, key->sexp /* point and ctx */);
1126 GNUNET_assert (0 == rc);
1127 slen = gcry_sexp_sprint (result, GCRYSEXP_FMT_DEFAULT, sdata_buf, sizeof (sdata_buf));
1128 GNUNET_assert (0 != slen);
1131 /* use broken version, insecure! */
1132 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("To be implemented: not secure at the moment, please read README\n"));
1133 slen = sprintf ((char*) sdata_buf, "FIXME-this is not key material");
1135 gcry_sexp_release (data);
1137 /* finally, get a string of the resulting S-expression and hash it to generate the key material */
1138 GNUNET_CRYPTO_hash (sdata_buf, slen, key_material);
1143 /* end of crypto_ecc.c */