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 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
392 "(genkey(ecdsa(curve 10:NIST P-521)))")))
394 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
397 if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
399 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
400 gcry_sexp_release (s_keyparam);
403 gcry_sexp_release (s_keyparam);
405 if (0 != (rc = gcry_pk_testkey (s_key)))
407 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
408 gcry_sexp_release (s_key);
412 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
419 * Try to read the private key from the given file.
421 * @param filename file to read the key from
422 * @return NULL on error
424 static struct GNUNET_CRYPTO_EccPrivateKey *
425 try_read_key (const char *filename)
427 struct GNUNET_CRYPTO_EccPrivateKey *ret;
428 struct GNUNET_DISK_FileHandle *fd;
431 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
434 /* hostkey file exists already, read it! */
435 if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
436 GNUNET_DISK_PERM_NONE)))
438 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
441 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
443 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
444 (void) GNUNET_DISK_file_close (fd);
449 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
454 LOG (GNUNET_ERROR_TYPE_ERROR,
455 _("File `%s' does not contain a valid private key (too long, %llu bytes). Deleting it.\n"),
457 (unsigned long long) fs);
458 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
459 if (0 != UNLINK (filename))
460 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
466 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
467 if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs)))
469 LOG (GNUNET_ERROR_TYPE_ERROR,
470 _("File `%s' does not contain a valid private key (failed decode, %llu bytes). Deleting it.\n"),
472 (unsigned long long) fs);
473 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
474 if (0 != UNLINK (filename))
475 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
479 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
485 * Wait for a short time (we're trying to lock a file or want
486 * to give another process a shot at finishing a disk write, etc.).
487 * Sleeps for 100ms (as that should be long enough for virtually all
488 * modern systems to context switch and allow another process to do
494 struct GNUNET_TIME_Relative timeout;
496 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
497 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
502 * Create a new private key by reading it from a file. If the
503 * files does not exist, create a new key and write it to the
504 * file. Caller must free return value. Note that this function
505 * can not guarantee that another process might not be trying
506 * the same operation on the same file at the same time.
507 * If the contents of the file
508 * are invalid the old file is deleted and a fresh key is
511 * @return new private key, NULL on error (for example,
514 struct GNUNET_CRYPTO_EccPrivateKey *
515 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
517 struct GNUNET_CRYPTO_EccPrivateKey *ret;
518 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
520 struct GNUNET_DISK_FileHandle *fd;
524 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
525 struct GNUNET_PeerIdentity pid;
527 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
529 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
531 fd = GNUNET_DISK_file_open (filename,
532 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
533 | GNUNET_DISK_OPEN_FAILIFEXISTS,
534 GNUNET_DISK_PERM_USER_READ |
535 GNUNET_DISK_PERM_USER_WRITE);
540 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
542 /* must exist but not be accessible, fail for good! */
543 if (0 != ACCESS (filename, R_OK))
544 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
546 GNUNET_break (0); /* what is going on!? */
551 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
557 GNUNET_DISK_file_lock (fd, 0,
558 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
565 LOG (GNUNET_ERROR_TYPE_ERROR,
566 _("Could not acquire lock on file `%s': %s...\n"), filename,
570 LOG (GNUNET_ERROR_TYPE_INFO,
571 _("Creating a new private key. This may take a while.\n"));
572 ret = ecc_key_create ();
573 GNUNET_assert (ret != NULL);
574 enc = GNUNET_CRYPTO_ecc_encode_key (ret);
575 GNUNET_assert (enc != NULL);
576 GNUNET_assert (ntohs (enc->size) ==
577 GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
580 GNUNET_DISK_file_sync (fd);
582 GNUNET_DISK_file_unlock (fd, 0,
583 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
584 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
585 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
586 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
587 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
588 LOG (GNUNET_ERROR_TYPE_INFO,
589 _("I am host `%s'. Stored new private key in `%s'.\n"),
590 GNUNET_i2s (&pid), filename);
593 /* hostkey file exists already, read it! */
594 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
595 GNUNET_DISK_PERM_NONE);
598 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
605 GNUNET_DISK_file_lock (fd, 0,
606 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
612 LOG (GNUNET_ERROR_TYPE_ERROR,
613 _("Could not acquire lock on file `%s': %s...\n"), filename,
615 LOG (GNUNET_ERROR_TYPE_ERROR,
617 ("This may be ok if someone is currently generating a hostkey.\n"));
622 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
624 /* eh, what!? File we opened is now gone!? */
625 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
627 GNUNET_DISK_file_unlock (fd, 0,
628 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
629 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
630 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
634 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
636 if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
638 /* maybe we got the read lock before the hostkey generating
639 * process had a chance to get the write lock; give it up! */
641 GNUNET_DISK_file_unlock (fd, 0,
642 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
643 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
646 LOG (GNUNET_ERROR_TYPE_ERROR,
648 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
649 filename, (unsigned int) fs,
650 (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
651 LOG (GNUNET_ERROR_TYPE_ERROR,
653 ("This may be ok if someone is currently generating a hostkey.\n"));
655 short_wait (); /* wait a bit longer! */
660 enc = GNUNET_malloc (fs);
661 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
662 len = ntohs (enc->size);
665 (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len))))
667 LOG (GNUNET_ERROR_TYPE_ERROR,
668 _("File `%s' does not contain a valid private key. Deleting it.\n"),
670 if (0 != UNLINK (filename))
672 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
677 GNUNET_DISK_file_unlock (fd, 0,
678 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
679 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
680 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
683 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
684 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
685 LOG (GNUNET_ERROR_TYPE_INFO,
686 _("I am host `%s'. Read private key from `%s'.\n"), GNUNET_i2s (&pid),
694 * Handle to cancel private key generation and state for the
695 * key generation operation.
697 struct GNUNET_CRYPTO_EccKeyGenerationContext
701 * Continuation to call upon completion.
703 GNUNET_CRYPTO_EccKeyCallback cont;
706 * Closure for 'cont'.
716 * Handle to the helper process which does the key generation.
718 struct GNUNET_OS_Process *gnunet_ecc;
721 * Handle to 'stdout' of gnunet-ecc. We 'read' on stdout to detect
722 * process termination (instead of messing with SIGCHLD).
724 struct GNUNET_DISK_PipeHandle *gnunet_ecc_out;
727 * Location where we store the private key if it already existed.
728 * (if this is used, 'filename', 'gnunet_ecc' and 'gnunet_ecc_out' will
731 struct GNUNET_CRYPTO_EccPrivateKey *pk;
734 * Task reading from 'gnunet_ecc_out' to wait for process termination.
736 GNUNET_SCHEDULER_TaskIdentifier read_task;
742 * Abort ECC key generation.
744 * @param gc key generation context to abort
747 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc)
749 if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
751 GNUNET_SCHEDULER_cancel (gc->read_task);
752 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
754 if (NULL != gc->gnunet_ecc)
756 (void) GNUNET_OS_process_kill (gc->gnunet_ecc, SIGKILL);
757 GNUNET_break (GNUNET_OK ==
758 GNUNET_OS_process_wait (gc->gnunet_ecc));
759 GNUNET_OS_process_destroy (gc->gnunet_ecc);
760 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
763 if (NULL != gc->filename)
765 if (0 != UNLINK (gc->filename))
766 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
767 GNUNET_free (gc->filename);
770 GNUNET_CRYPTO_ecc_key_free (gc->pk);
776 * Task called upon shutdown or process termination of 'gnunet-ecc' during
777 * ECC key generation. Check where we are and perform the appropriate
780 * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
781 * @param tc scheduler context
784 check_key_generation_completion (void *cls,
785 const struct GNUNET_SCHEDULER_TaskContext *tc)
787 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
788 struct GNUNET_CRYPTO_EccPrivateKey *pk;
790 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
791 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
793 gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
794 GNUNET_CRYPTO_ecc_key_create_stop (gc);
797 GNUNET_assert (GNUNET_OK ==
798 GNUNET_OS_process_wait (gc->gnunet_ecc));
799 GNUNET_OS_process_destroy (gc->gnunet_ecc);
800 gc->gnunet_ecc = NULL;
801 if (NULL == (pk = try_read_key (gc->filename)))
804 gc->cont (gc->cont_cls, NULL, _("gnunet-ecc failed"));
805 GNUNET_CRYPTO_ecc_key_create_stop (gc);
808 gc->cont (gc->cont_cls, pk, NULL);
809 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
810 GNUNET_free (gc->filename);
816 * Return the private ECC key which already existed on disk
817 * (asynchronously) to the caller.
819 * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
820 * @param tc scheduler context (unused)
823 async_return_key (void *cls,
824 const struct GNUNET_SCHEDULER_TaskContext *tc)
826 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
828 gc->cont (gc->cont_cls,
836 * Create a new private key by reading it from a file. If the files
837 * does not exist, create a new key and write it to the file. If the
838 * contents of the file are invalid the old file is deleted and a
839 * fresh key is created.
841 * @param filename name of file to use for storage
842 * @param cont function to call when done (or on errors)
843 * @param cont_cls closure for 'cont'
844 * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
846 struct GNUNET_CRYPTO_EccKeyGenerationContext *
847 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
848 GNUNET_CRYPTO_EccKeyCallback cont,
851 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc;
852 struct GNUNET_CRYPTO_EccPrivateKey *pk;
853 const char *weak_random;
855 if (NULL != (pk = try_read_key (filename)))
857 /* quick happy ending: key already exists! */
858 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
861 gc->cont_cls = cont_cls;
862 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
866 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
867 gc->filename = GNUNET_strdup (filename);
869 gc->cont_cls = cont_cls;
870 gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
874 if (NULL == gc->gnunet_ecc_out)
876 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
877 GNUNET_free (gc->filename);
883 GNUNET_CRYPTO_random_is_weak ())
885 gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
886 GNUNET_OS_INHERIT_STD_ERR,
894 if (NULL == gc->gnunet_ecc)
896 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
897 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
898 GNUNET_free (gc->filename);
902 GNUNET_assert (GNUNET_OK ==
903 GNUNET_DISK_pipe_close_end (gc->gnunet_ecc_out,
904 GNUNET_DISK_PIPE_END_WRITE));
905 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
906 GNUNET_DISK_pipe_handle (gc->gnunet_ecc_out,
907 GNUNET_DISK_PIPE_END_READ),
908 &check_key_generation_completion,
915 * Setup a hostkey file for a peer given the name of the
916 * configuration file (!). This function is used so that
917 * at a later point code can be certain that reading a
918 * hostkey is fast (for example in time-dependent testcases).
920 * @param cfg_name name of the configuration file to use
923 GNUNET_CRYPTO_ecc_setup_hostkey (const char *cfg_name)
925 struct GNUNET_CONFIGURATION_Handle *cfg;
926 struct GNUNET_CRYPTO_EccPrivateKey *pk;
929 cfg = GNUNET_CONFIGURATION_create ();
930 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
932 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
934 pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
936 GNUNET_CRYPTO_ecc_key_free (pk);
939 GNUNET_CONFIGURATION_destroy (cfg);
944 * Convert the data specified in the given purpose argument to an
945 * S-expression suitable for signature operations.
947 * @param purpose data to convert
948 * @return converted s-expression
951 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
953 struct GNUNET_HashCode hc;
957 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
958 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
959 bufSize = strlen (FORMATSTRING) + 1;
963 memcpy (buff, FORMATSTRING, bufSize);
967 ("0123456789012345678901234567890123456789012345678901234567890123))")
968 - 1], &hc, sizeof (struct GNUNET_HashCode));
969 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
977 * Sign a given block.
979 * @param key private key to use for the signing
980 * @param purpose what to sign (size, purpose)
981 * @param sig where to write the signature
982 * @return GNUNET_SYSERR on error, GNUNET_OK on success
985 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
986 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
987 struct GNUNET_CRYPTO_EccSignature *sig)
993 data = data_to_pkcs1 (purpose);
994 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
995 gcry_sexp_release (data);
996 ssize = gcry_sexp_sprint (result,
997 GCRYSEXP_FMT_DEFAULT,
999 GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH);
1003 return GNUNET_SYSERR;
1005 sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
1006 /* padd with zeros */
1007 memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH - ssize);
1008 gcry_sexp_release (result);
1016 * @param purpose what is the purpose that the signature should have?
1017 * @param validate block to validate (size, purpose, data)
1018 * @param sig signature that is being validated
1019 * @param publicKey public key of the signer
1020 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1023 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1024 const struct GNUNET_CRYPTO_EccSignaturePurpose
1026 const struct GNUNET_CRYPTO_EccSignature *sig,
1027 const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1031 gcry_sexp_t sigdata;
1037 if (purpose != ntohl (validate->purpose))
1038 return GNUNET_SYSERR; /* purpose mismatch */
1039 size = ntohs (sig->size);
1040 if ( (size < sizeof (uint16_t)) ||
1041 (size > GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1042 return GNUNET_SYSERR; /* size out of range */
1043 data = data_to_pkcs1 (validate);
1045 gcry_sexp_sscan (&sigdata, &erroff,
1046 sig->sexpr, size - sizeof (uint16_t)));
1047 if (! (psexp = decode_public_key (publicKey)))
1049 gcry_sexp_release (data);
1050 gcry_sexp_release (sigdata);
1051 return GNUNET_SYSERR;
1053 rc = gcry_pk_verify (sigdata, data, psexp);
1054 gcry_sexp_release (psexp);
1055 gcry_sexp_release (data);
1056 gcry_sexp_release (sigdata);
1059 LOG (GNUNET_ERROR_TYPE_WARNING,
1060 _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1061 __LINE__, gcry_strerror (rc));
1062 return GNUNET_SYSERR;
1068 /* end of crypto_ecc.c */