2 This file is part of GNUnet.
3 (C) 2012, 2013 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,
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 */
267 if (0 != (rc = gcry_pk_testkey (result)))
269 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
270 gcry_sexp_release (result);
279 * Encode the private key in a format suitable for
280 * storing it into a file.
282 * @param key key to encode
283 * @return encoding of the private key.
284 * The first 4 bytes give the size of the array, as usual.
286 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
287 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key)
289 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *retval;
295 if (0 != gcry_pk_testkey (key->sexp))
301 size = gcry_sexp_sprint (key->sexp,
302 GCRYSEXP_FMT_DEFAULT,
303 &buf[2], sizeof (buf) - sizeof (uint16_t));
309 GNUNET_assert (size < 65536 - sizeof (uint16_t));
310 be = htons ((uint16_t) size + (sizeof (be)));
311 memcpy (buf, &be, sizeof (be));
313 retval = GNUNET_malloc (size);
314 memcpy (retval, buf, size);
320 * Decode the private key from the file-format back
321 * to the "normal", internal format.
323 * @param buf the buffer where the private key data is stored
324 * @param len the length of the data in 'buffer'
325 * @param validate GNUNET_YES to validate that the key is well-formed,
326 * GNUNET_NO if the key comes from a totally trusted source
327 * and validation is considered too expensive
328 * @return NULL on error
330 struct GNUNET_CRYPTO_EccPrivateKey *
331 GNUNET_CRYPTO_ecc_decode_key (const char *buf,
335 struct GNUNET_CRYPTO_EccPrivateKey *ret;
341 if (len < sizeof (uint16_t))
343 memcpy (&be, buf, sizeof (be));
344 if (len < ntohs (be))
347 if (0 != (rc = gcry_sexp_sscan (&sexp,
350 len - sizeof (uint16_t))))
352 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
355 if ( (GNUNET_YES == validate) &&
356 (0 != (rc = gcry_pk_testkey (sexp))) )
358 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
361 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
368 * Create a new private key. Caller must free return value.
370 * @return fresh private key
372 struct GNUNET_CRYPTO_EccPrivateKey *
373 GNUNET_CRYPTO_ecc_key_create ()
375 struct GNUNET_CRYPTO_EccPrivateKey *ret;
377 gcry_sexp_t s_keyparam;
380 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
381 "(genkey(ecdsa(curve \"" CURVE "\")))")))
383 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
386 if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
388 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
389 gcry_sexp_release (s_keyparam);
392 gcry_sexp_release (s_keyparam);
394 if (0 != (rc = gcry_pk_testkey (s_key)))
396 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
397 gcry_sexp_release (s_key);
401 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
408 * Try to read the private key from the given file.
410 * @param filename file to read the key from
411 * @return NULL on error
413 static struct GNUNET_CRYPTO_EccPrivateKey *
414 try_read_key (const char *filename)
416 struct GNUNET_CRYPTO_EccPrivateKey *ret;
417 struct GNUNET_DISK_FileHandle *fd;
420 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
423 /* key file exists already, read it! */
424 if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
425 GNUNET_DISK_PERM_NONE)))
427 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
430 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
432 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
433 (void) GNUNET_DISK_file_close (fd);
438 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
443 LOG (GNUNET_ERROR_TYPE_ERROR,
444 _("File `%s' does not contain a valid private key (too long, %llu bytes). Deleting it.\n"),
446 (unsigned long long) fs);
447 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
448 if (0 != UNLINK (filename))
449 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
455 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
456 if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs, GNUNET_YES)))
458 LOG (GNUNET_ERROR_TYPE_ERROR,
459 _("File `%s' does not contain a valid private key (failed decode, %llu bytes). Deleting it.\n"),
461 (unsigned long long) fs);
462 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
463 if (0 != UNLINK (filename))
464 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
468 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
474 * Wait for a short time (we're trying to lock a file or want
475 * to give another process a shot at finishing a disk write, etc.).
476 * Sleeps for 100ms (as that should be long enough for virtually all
477 * modern systems to context switch and allow another process to do
483 struct GNUNET_TIME_Relative timeout;
485 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
486 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
491 * Create a new private key by reading it from a file. If the
492 * files does not exist, create a new key and write it to the
493 * file. Caller must free return value. Note that this function
494 * can not guarantee that another process might not be trying
495 * the same operation on the same file at the same time.
496 * If the contents of the file
497 * are invalid the old file is deleted and a fresh key is
500 * @return new private key, NULL on error (for example,
503 struct GNUNET_CRYPTO_EccPrivateKey *
504 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
506 struct GNUNET_CRYPTO_EccPrivateKey *ret;
507 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
509 struct GNUNET_DISK_FileHandle *fd;
513 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
514 struct GNUNET_PeerIdentity pid;
516 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
518 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
520 fd = GNUNET_DISK_file_open (filename,
521 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
522 | GNUNET_DISK_OPEN_FAILIFEXISTS,
523 GNUNET_DISK_PERM_USER_READ |
524 GNUNET_DISK_PERM_USER_WRITE);
529 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
531 /* must exist but not be accessible, fail for good! */
532 if (0 != ACCESS (filename, R_OK))
533 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
535 GNUNET_break (0); /* what is going on!? */
540 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
546 GNUNET_DISK_file_lock (fd, 0,
547 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
554 LOG (GNUNET_ERROR_TYPE_ERROR,
555 _("Could not acquire lock on file `%s': %s...\n"), filename,
559 LOG (GNUNET_ERROR_TYPE_INFO,
560 _("Creating a new private key. This may take a while.\n"));
561 ret = GNUNET_CRYPTO_ecc_key_create ();
562 GNUNET_assert (ret != NULL);
563 enc = GNUNET_CRYPTO_ecc_encode_key (ret);
564 GNUNET_assert (enc != NULL);
565 GNUNET_assert (ntohs (enc->size) ==
566 GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
569 GNUNET_DISK_file_sync (fd);
571 GNUNET_DISK_file_unlock (fd, 0,
572 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
573 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
574 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
575 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
576 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
579 /* key 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 private key.\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 key 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 key 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 key.\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, GNUNET_YES))))
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);
677 * Handle to cancel private key generation and state for the
678 * key generation operation.
680 struct GNUNET_CRYPTO_EccKeyGenerationContext
684 * Continuation to call upon completion.
686 GNUNET_CRYPTO_EccKeyCallback cont;
689 * Closure for 'cont'.
699 * Handle to the helper process which does the key generation.
701 struct GNUNET_OS_Process *gnunet_ecc;
704 * Handle to 'stdout' of gnunet-ecc. We 'read' on stdout to detect
705 * process termination (instead of messing with SIGCHLD).
707 struct GNUNET_DISK_PipeHandle *gnunet_ecc_out;
710 * Location where we store the private key if it already existed.
711 * (if this is used, 'filename', 'gnunet_ecc' and 'gnunet_ecc_out' will
714 struct GNUNET_CRYPTO_EccPrivateKey *pk;
717 * Task reading from 'gnunet_ecc_out' to wait for process termination.
719 GNUNET_SCHEDULER_TaskIdentifier read_task;
725 * Abort ECC key generation.
727 * @param gc key generation context to abort
730 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc)
732 if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
734 GNUNET_SCHEDULER_cancel (gc->read_task);
735 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
737 if (NULL != gc->gnunet_ecc)
739 (void) GNUNET_OS_process_kill (gc->gnunet_ecc, SIGKILL);
740 GNUNET_break (GNUNET_OK ==
741 GNUNET_OS_process_wait (gc->gnunet_ecc));
742 GNUNET_OS_process_destroy (gc->gnunet_ecc);
743 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
746 if (NULL != gc->filename)
748 if (0 != UNLINK (gc->filename))
749 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
750 GNUNET_free (gc->filename);
753 GNUNET_CRYPTO_ecc_key_free (gc->pk);
759 * Task called upon shutdown or process termination of 'gnunet-ecc' during
760 * ECC key generation. Check where we are and perform the appropriate
763 * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
764 * @param tc scheduler context
767 check_key_generation_completion (void *cls,
768 const struct GNUNET_SCHEDULER_TaskContext *tc)
770 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
771 struct GNUNET_CRYPTO_EccPrivateKey *pk;
773 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
774 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
776 gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
777 GNUNET_CRYPTO_ecc_key_create_stop (gc);
780 GNUNET_assert (GNUNET_OK ==
781 GNUNET_OS_process_wait (gc->gnunet_ecc));
782 GNUNET_OS_process_destroy (gc->gnunet_ecc);
783 gc->gnunet_ecc = NULL;
784 if (NULL == (pk = try_read_key (gc->filename)))
787 gc->cont (gc->cont_cls, NULL, _("gnunet-ecc failed"));
788 GNUNET_CRYPTO_ecc_key_create_stop (gc);
791 gc->cont (gc->cont_cls, pk, NULL);
792 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
793 GNUNET_free (gc->filename);
799 * Return the private ECC key which already existed on disk
800 * (asynchronously) to the caller.
802 * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
803 * @param tc scheduler context (unused)
806 async_return_key (void *cls,
807 const struct GNUNET_SCHEDULER_TaskContext *tc)
809 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
811 gc->cont (gc->cont_cls,
819 * Create a new private key by reading it from a file. If the files
820 * does not exist, create a new key and write it to the file. If the
821 * contents of the file are invalid the old file is deleted and a
822 * fresh key is created.
824 * @param filename name of file to use for storage
825 * @param cont function to call when done (or on errors)
826 * @param cont_cls closure for 'cont'
827 * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
829 struct GNUNET_CRYPTO_EccKeyGenerationContext *
830 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
831 GNUNET_CRYPTO_EccKeyCallback cont,
834 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc;
835 struct GNUNET_CRYPTO_EccPrivateKey *pk;
837 if (NULL != (pk = try_read_key (filename)))
839 /* quick happy ending: key already exists! */
840 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
843 gc->cont_cls = cont_cls;
844 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
848 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
849 gc->filename = GNUNET_strdup (filename);
851 gc->cont_cls = cont_cls;
852 gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
856 if (NULL == gc->gnunet_ecc_out)
858 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
859 GNUNET_free (gc->filename);
863 gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
864 GNUNET_OS_INHERIT_STD_ERR,
871 if (NULL == gc->gnunet_ecc)
873 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
874 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
875 GNUNET_free (gc->filename);
879 GNUNET_assert (GNUNET_OK ==
880 GNUNET_DISK_pipe_close_end (gc->gnunet_ecc_out,
881 GNUNET_DISK_PIPE_END_WRITE));
882 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
883 GNUNET_DISK_pipe_handle (gc->gnunet_ecc_out,
884 GNUNET_DISK_PIPE_END_READ),
885 &check_key_generation_completion,
892 * Setup a key file for a peer given the name of the
893 * configuration file (!). This function is used so that
894 * at a later point code can be certain that reading a
895 * key is fast (for example in time-dependent testcases).
897 * @param cfg_name name of the configuration file to use
900 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
902 struct GNUNET_CONFIGURATION_Handle *cfg;
903 struct GNUNET_CRYPTO_EccPrivateKey *pk;
906 cfg = GNUNET_CONFIGURATION_create ();
907 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
909 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
911 pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
913 GNUNET_CRYPTO_ecc_key_free (pk);
916 GNUNET_CONFIGURATION_destroy (cfg);
921 * Retrieve the identity of the host's peer.
923 * @param cfg configuration to use
924 * @param dst pointer to where to write the peer identity
925 * @return GNUNET_OK on success, GNUNET_SYSERR if the identity
926 * could not be retrieved
929 GNUNET_CRYPTO_get_host_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
930 struct GNUNET_PeerIdentity *dst)
932 struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
933 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded my_public_key;
937 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY",
940 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
941 _("Lacking key configuration settings.\n"));
942 return GNUNET_SYSERR;
944 if (NULL == (my_private_key = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile)))
946 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
947 _("Could not access hostkey file `%s'.\n"), keyfile);
948 GNUNET_free (keyfile);
949 return GNUNET_SYSERR;
951 GNUNET_free (keyfile);
952 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
953 GNUNET_CRYPTO_ecc_key_free (my_private_key);
954 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &dst->hashPubKey);
960 * Convert the data specified in the given purpose argument to an
961 * S-expression suitable for signature operations.
963 * @param purpose data to convert
964 * @return converted s-expression
967 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
969 struct GNUNET_CRYPTO_ShortHashCode hc;
973 GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
974 #define FORMATSTRING "(4:data(5:flags3:raw)(5:value32:01234567890123456789012345678901))"
975 bufSize = strlen (FORMATSTRING) + 1;
979 memcpy (buff, FORMATSTRING, bufSize);
983 ("01234567890123456789012345678901))")
984 - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
985 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
993 * Sign a given block.
995 * @param key private key to use for the signing
996 * @param purpose what to sign (size, purpose)
997 * @param sig where to write the signature
998 * @return GNUNET_SYSERR on error, GNUNET_OK on success
1001 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1002 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1003 struct GNUNET_CRYPTO_EccSignature *sig)
1010 data = data_to_pkcs1 (purpose);
1011 if (0 != (rc = gcry_pk_sign (&result, data, key->sexp)))
1013 LOG (GNUNET_ERROR_TYPE_WARNING,
1014 _("ECC signing failed at %s:%d: %s\n"), __FILE__,
1015 __LINE__, gcry_strerror (rc));
1016 gcry_sexp_release (data);
1017 return GNUNET_SYSERR;
1019 gcry_sexp_release (data);
1020 ssize = gcry_sexp_sprint (result,
1021 GCRYSEXP_FMT_DEFAULT,
1023 GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH);
1027 return GNUNET_SYSERR;
1029 sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
1030 /* padd with zeros */
1031 memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - ssize);
1032 gcry_sexp_release (result);
1040 * @param purpose what is the purpose that the signature should have?
1041 * @param validate block to validate (size, purpose, data)
1042 * @param sig signature that is being validated
1043 * @param publicKey public key of the signer
1044 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1047 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1048 const struct GNUNET_CRYPTO_EccSignaturePurpose
1050 const struct GNUNET_CRYPTO_EccSignature *sig,
1051 const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1055 gcry_sexp_t sigdata;
1061 if (purpose != ntohl (validate->purpose))
1062 return GNUNET_SYSERR; /* purpose mismatch */
1063 size = ntohs (sig->size);
1064 if ( (size < sizeof (uint16_t)) ||
1065 (size > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1066 return GNUNET_SYSERR; /* size out of range */
1067 data = data_to_pkcs1 (validate);
1069 gcry_sexp_sscan (&sigdata, &erroff,
1070 sig->sexpr, size - sizeof (uint16_t)));
1071 if (! (psexp = decode_public_key (publicKey)))
1073 gcry_sexp_release (data);
1074 gcry_sexp_release (sigdata);
1075 return GNUNET_SYSERR;
1077 rc = gcry_pk_verify (sigdata, data, psexp);
1078 gcry_sexp_release (psexp);
1079 gcry_sexp_release (data);
1080 gcry_sexp_release (sigdata);
1083 LOG (GNUNET_ERROR_TYPE_WARNING,
1084 _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1085 __LINE__, gcry_strerror (rc));
1086 return GNUNET_SYSERR;
1093 * Derive key material from a public and a private ECC key.
1095 * @param key private key to use for the ECDH (x)
1096 * @param pub public key to use for the ECDY (yG)
1097 * @param key_material where to write the key material (xyG)
1098 * @return GNUNET_SYSERR on error, GNUNET_OK on success
1101 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1102 const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub,
1103 struct GNUNET_HashCode *key_material)
1108 unsigned char sdata_buf[2048]; /* big enough to print dh-shared-secret as S-expression */
1109 gcry_mpi_point_t result;
1114 gcry_mpi_t result_x;
1115 gcry_mpi_t result_y;
1117 /* first, extract the q = dP value from the public key */
1118 if (! (psexp = decode_public_key (pub)))
1119 return GNUNET_SYSERR;
1120 if (0 != (rc = gcry_mpi_ec_new (&ctx, psexp, NULL)))
1122 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc); /* erroff gives more info */
1123 return GNUNET_SYSERR;
1125 gcry_sexp_release (psexp);
1126 q = gcry_mpi_ec_get_point ("q", ctx, 0);
1127 gcry_ctx_release (ctx);
1129 /* second, extract the d value from our private key */
1130 rc = key_from_sexp (&d, key->sexp, "private-key", "d");
1132 rc = key_from_sexp (&d, key->sexp, "ecc", "d");
1136 gcry_mpi_point_release (q);
1137 return GNUNET_SYSERR;
1140 /* create a new context for definitively the correct curve;
1141 theoretically the 'public_key' might not use the right curve */
1142 if (0 != (rc = gcry_mpi_ec_new (&ctx, NULL, "NIST P-256")))
1144 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc); /* erroff gives more info */
1145 gcry_mpi_release (d);
1146 gcry_mpi_point_release (q);
1147 return GNUNET_SYSERR;
1150 /* then call the 'multiply' function, to compute the product */
1151 GNUNET_assert (NULL != ctx);
1152 result = gcry_mpi_point_new (0);
1153 gcry_mpi_ec_mul (result, d, q, ctx);
1154 gcry_mpi_point_release (q);
1155 gcry_mpi_release (d);
1157 /* finally, convert point to string for hashing */
1158 result_x = gcry_mpi_new (256);
1159 result_y = gcry_mpi_new (256);
1160 if (gcry_mpi_ec_get_affine (result_x, result_y, result, ctx))
1162 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
1163 gcry_mpi_point_release (result);
1164 gcry_ctx_release (ctx);
1165 return GNUNET_SYSERR;
1167 gcry_mpi_point_release (result);
1168 gcry_ctx_release (ctx);
1169 if (0 != (rc = gcry_sexp_build (&psexp, &erroff,
1170 "(dh-shared-secret (x %m)(y %m))",
1174 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
1175 gcry_mpi_release (result_x);
1176 gcry_mpi_release (result_y);
1177 return GNUNET_SYSERR;
1179 gcry_mpi_release (result_x);
1180 gcry_mpi_release (result_y);
1181 slen = gcry_sexp_sprint (psexp, GCRYSEXP_FMT_DEFAULT, sdata_buf, sizeof (sdata_buf));
1182 GNUNET_assert (0 != slen);
1183 gcry_sexp_release (psexp);
1184 /* finally, get a string of the resulting S-expression and hash it to generate the key material */
1185 GNUNET_CRYPTO_hash (sdata_buf, slen, key_material);
1190 /* end of crypto_ecc.c */