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 * - fix public key generation; somehow the result is currently considered invalid by libgcrypt
29 * => suspect that libgcrypt does NOT take pabgn from "CURVE" for public key if not
35 #include "gnunet_common.h"
36 #include "gnunet_util_lib.h"
38 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS || 1
40 #define CURVE "NIST P-521"
42 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
44 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
46 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
49 * Log an error message at log-level 'level' that indicates
50 * a failure of the command 'cmd' with the message given
51 * by gcry_strerror(rc).
53 #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);
57 * The private information of an ECC private key.
59 struct GNUNET_CRYPTO_EccPrivateKey
63 * Libgcrypt S-expression for the ECC key.
70 * Free memory occupied by ECC key
72 * @param privatekey pointer to the memory to free
75 GNUNET_CRYPTO_ecc_key_free (struct GNUNET_CRYPTO_EccPrivateKey *privatekey)
77 gcry_sexp_release (privatekey->sexp);
78 GNUNET_free (privatekey);
83 * Extract values from an S-expression.
85 * @param array where to store the result(s)
86 * @param sexp S-expression to parse
87 * @param topname top-level name in the S-expression that is of interest
88 * @param elems names of the elements to extract
89 * @return 0 on success
92 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
101 list = gcry_sexp_find_token (sexp, topname, 0);
104 l2 = gcry_sexp_cadr (list);
105 gcry_sexp_release (list);
111 for (s = elems; *s; s++, idx++)
113 l2 = gcry_sexp_find_token (list, s, 1);
116 for (i = 0; i < idx; i++)
118 gcry_free (array[i]);
121 gcry_sexp_release (list);
122 return 3; /* required parameter not found */
124 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
125 gcry_sexp_release (l2);
128 for (i = 0; i < idx; i++)
130 gcry_free (array[i]);
133 gcry_sexp_release (list);
134 return 4; /* required parameter is invalid */
137 gcry_sexp_release (list);
143 * Extract the public key for the given private key.
145 * @param priv the private key
146 * @param pub where to write the public key
149 GNUNET_CRYPTO_ecc_key_get_public (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
150 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
156 memset (pub, 0, sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
157 rc = key_from_sexp (&skey, priv->sexp, "public-key", "q");
159 rc = key_from_sexp (&skey, priv->sexp, "private-key", "q");
161 rc = key_from_sexp (&skey, priv->sexp, "ecc", "q");
162 GNUNET_assert (0 == rc);
163 pub->size = htons (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
164 size = GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH;
166 gcry_mpi_print (GCRYMPI_FMT_USG, pub->key, size, &size,
168 pub->len = htons (size);
169 gcry_mpi_release (skey);
174 * Convert a public key to a string.
176 * @param pub key to convert
177 * @return string representing 'pub'
180 GNUNET_CRYPTO_ecc_public_key_to_string (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
183 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
187 keylen += 5 - keylen % 5;
189 pubkeybuf = GNUNET_malloc (keylen + 1);
190 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
191 sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded),
196 GNUNET_free (pubkeybuf);
205 * Convert a string representing a public key to a public key.
207 * @param enc encoded public key
208 * @param enclen number of bytes in enc (without 0-terminator)
209 * @param pub where to store the public key
210 * @return GNUNET_OK on success
213 GNUNET_CRYPTO_ecc_public_key_from_string (const char *enc,
215 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
217 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
220 keylen += 5 - keylen % 5;
222 if (enclen != keylen)
223 return GNUNET_SYSERR;
225 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
226 (unsigned char*) pub,
227 sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)))
228 return GNUNET_SYSERR;
229 if ( (ntohs (pub->size) != sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) ||
230 (ntohs (pub->len) > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH) )
231 return GNUNET_SYSERR;
237 * Convert the given public key from the network format to the
238 * S-expression that can be used by libgcrypt.
240 * @param publicKey public key to decode
241 * @return NULL on error
244 decode_public_key (const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *publicKey)
252 if (ntohs (publicKey->len) > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH)
257 size = ntohs (publicKey->len);
258 if (0 != (rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG, publicKey->key, size, &size)))
260 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
264 rc = gcry_sexp_build (&result, &erroff,
265 "(public-key(ecdsa(curve \"" CURVE "\")(q %m)))",
267 gcry_mpi_release (q);
270 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
273 // FIXME: is this key expected to pass pk_testkey?
276 if (0 != (rc = gcry_pk_testkey (result)))
278 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
279 gcry_sexp_release (result);
289 * Encode the private key in a format suitable for
290 * storing it into a file.
292 * @param key key to encode
293 * @return encoding of the private key.
294 * The first 4 bytes give the size of the array, as usual.
296 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
297 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key)
299 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *retval;
305 if (0 != gcry_pk_testkey (key->sexp))
311 size = gcry_sexp_sprint (key->sexp,
312 GCRYSEXP_FMT_DEFAULT,
313 &buf[2], sizeof (buf) - sizeof (uint16_t));
319 GNUNET_assert (size < 65536 - sizeof (uint16_t));
320 be = htons ((uint16_t) size + (sizeof (be)));
321 memcpy (buf, &be, sizeof (be));
323 retval = GNUNET_malloc (size);
324 memcpy (retval, buf, size);
330 * Decode the private key from the file-format back
331 * to the "normal", internal format.
333 * @param buf the buffer where the private key data is stored
334 * @param len the length of the data in 'buffer'
335 * @return NULL on error
337 struct GNUNET_CRYPTO_EccPrivateKey *
338 GNUNET_CRYPTO_ecc_decode_key (const char *buf,
341 struct GNUNET_CRYPTO_EccPrivateKey *ret;
347 if (len < sizeof (uint16_t))
349 memcpy (&be, buf, sizeof (be));
350 if (len != ntohs (be))
352 if (0 != (rc = gcry_sexp_sscan (&sexp,
355 len - sizeof (uint16_t))))
357 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
360 if (0 != (rc = gcry_pk_testkey (sexp)))
362 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
365 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
372 * Create a new private key. Caller must free return value.
374 * @return fresh private key
376 static struct GNUNET_CRYPTO_EccPrivateKey *
379 struct GNUNET_CRYPTO_EccPrivateKey *ret;
381 gcry_sexp_t s_keyparam;
384 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
385 "(genkey(ecdsa(curve \"" CURVE "\")))")))
387 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
390 if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
392 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
393 gcry_sexp_release (s_keyparam);
396 gcry_sexp_release (s_keyparam);
398 if (0 != (rc = gcry_pk_testkey (s_key)))
400 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
401 gcry_sexp_release (s_key);
405 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
412 * Try to read the private key from the given file.
414 * @param filename file to read the key from
415 * @return NULL on error
417 static struct GNUNET_CRYPTO_EccPrivateKey *
418 try_read_key (const char *filename)
420 struct GNUNET_CRYPTO_EccPrivateKey *ret;
421 struct GNUNET_DISK_FileHandle *fd;
424 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
427 /* key file exists already, read it! */
428 if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
429 GNUNET_DISK_PERM_NONE)))
431 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
434 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
436 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
437 (void) GNUNET_DISK_file_close (fd);
442 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
447 LOG (GNUNET_ERROR_TYPE_ERROR,
448 _("File `%s' does not contain a valid private key (too long, %llu bytes). Deleting it.\n"),
450 (unsigned long long) fs);
451 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
452 if (0 != UNLINK (filename))
453 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
459 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
460 if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs)))
462 LOG (GNUNET_ERROR_TYPE_ERROR,
463 _("File `%s' does not contain a valid private key (failed decode, %llu bytes). Deleting it.\n"),
465 (unsigned long long) fs);
466 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
467 if (0 != UNLINK (filename))
468 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
472 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
478 * Wait for a short time (we're trying to lock a file or want
479 * to give another process a shot at finishing a disk write, etc.).
480 * Sleeps for 100ms (as that should be long enough for virtually all
481 * modern systems to context switch and allow another process to do
487 struct GNUNET_TIME_Relative timeout;
489 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
490 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
495 * Create a new private key by reading it from a file. If the
496 * files does not exist, create a new key and write it to the
497 * file. Caller must free return value. Note that this function
498 * can not guarantee that another process might not be trying
499 * the same operation on the same file at the same time.
500 * If the contents of the file
501 * are invalid the old file is deleted and a fresh key is
504 * @return new private key, NULL on error (for example,
507 struct GNUNET_CRYPTO_EccPrivateKey *
508 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
510 struct GNUNET_CRYPTO_EccPrivateKey *ret;
511 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
513 struct GNUNET_DISK_FileHandle *fd;
517 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
518 struct GNUNET_PeerIdentity pid;
520 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
522 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
524 fd = GNUNET_DISK_file_open (filename,
525 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
526 | GNUNET_DISK_OPEN_FAILIFEXISTS,
527 GNUNET_DISK_PERM_USER_READ |
528 GNUNET_DISK_PERM_USER_WRITE);
533 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
535 /* must exist but not be accessible, fail for good! */
536 if (0 != ACCESS (filename, R_OK))
537 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
539 GNUNET_break (0); /* what is going on!? */
544 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
550 GNUNET_DISK_file_lock (fd, 0,
551 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
558 LOG (GNUNET_ERROR_TYPE_ERROR,
559 _("Could not acquire lock on file `%s': %s...\n"), filename,
563 LOG (GNUNET_ERROR_TYPE_INFO,
564 _("Creating a new private key. This may take a while.\n"));
565 ret = ecc_key_create ();
566 GNUNET_assert (ret != NULL);
567 enc = GNUNET_CRYPTO_ecc_encode_key (ret);
568 GNUNET_assert (enc != NULL);
569 GNUNET_assert (ntohs (enc->size) ==
570 GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
573 GNUNET_DISK_file_sync (fd);
575 GNUNET_DISK_file_unlock (fd, 0,
576 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
577 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
578 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
579 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
580 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
583 /* key file exists already, read it! */
584 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
585 GNUNET_DISK_PERM_NONE);
588 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
595 GNUNET_DISK_file_lock (fd, 0,
596 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
602 LOG (GNUNET_ERROR_TYPE_ERROR,
603 _("Could not acquire lock on file `%s': %s...\n"), filename,
605 LOG (GNUNET_ERROR_TYPE_ERROR,
607 ("This may be ok if someone is currently generating a private key.\n"));
612 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
614 /* eh, what!? File we opened is now gone!? */
615 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
617 GNUNET_DISK_file_unlock (fd, 0,
618 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
619 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
620 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
624 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
626 if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
628 /* maybe we got the read lock before the key generating
629 * process had a chance to get the write lock; give it up! */
631 GNUNET_DISK_file_unlock (fd, 0,
632 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
633 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
636 LOG (GNUNET_ERROR_TYPE_ERROR,
638 ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
639 filename, (unsigned int) fs,
640 (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
641 LOG (GNUNET_ERROR_TYPE_ERROR,
643 ("This may be ok if someone is currently generating a key.\n"));
645 short_wait (); /* wait a bit longer! */
650 enc = GNUNET_malloc (fs);
651 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
652 len = ntohs (enc->size);
655 (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len))))
657 LOG (GNUNET_ERROR_TYPE_ERROR,
658 _("File `%s' does not contain a valid private key. Deleting it.\n"),
660 if (0 != UNLINK (filename))
662 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
667 GNUNET_DISK_file_unlock (fd, 0,
668 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
669 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
670 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
673 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
674 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
681 * Handle to cancel private key generation and state for the
682 * key generation operation.
684 struct GNUNET_CRYPTO_EccKeyGenerationContext
688 * Continuation to call upon completion.
690 GNUNET_CRYPTO_EccKeyCallback cont;
693 * Closure for 'cont'.
703 * Handle to the helper process which does the key generation.
705 struct GNUNET_OS_Process *gnunet_ecc;
708 * Handle to 'stdout' of gnunet-ecc. We 'read' on stdout to detect
709 * process termination (instead of messing with SIGCHLD).
711 struct GNUNET_DISK_PipeHandle *gnunet_ecc_out;
714 * Location where we store the private key if it already existed.
715 * (if this is used, 'filename', 'gnunet_ecc' and 'gnunet_ecc_out' will
718 struct GNUNET_CRYPTO_EccPrivateKey *pk;
721 * Task reading from 'gnunet_ecc_out' to wait for process termination.
723 GNUNET_SCHEDULER_TaskIdentifier read_task;
729 * Abort ECC key generation.
731 * @param gc key generation context to abort
734 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc)
736 if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
738 GNUNET_SCHEDULER_cancel (gc->read_task);
739 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
741 if (NULL != gc->gnunet_ecc)
743 (void) GNUNET_OS_process_kill (gc->gnunet_ecc, SIGKILL);
744 GNUNET_break (GNUNET_OK ==
745 GNUNET_OS_process_wait (gc->gnunet_ecc));
746 GNUNET_OS_process_destroy (gc->gnunet_ecc);
747 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
750 if (NULL != gc->filename)
752 if (0 != UNLINK (gc->filename))
753 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
754 GNUNET_free (gc->filename);
757 GNUNET_CRYPTO_ecc_key_free (gc->pk);
763 * Task called upon shutdown or process termination of 'gnunet-ecc' during
764 * ECC key generation. Check where we are and perform the appropriate
767 * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
768 * @param tc scheduler context
771 check_key_generation_completion (void *cls,
772 const struct GNUNET_SCHEDULER_TaskContext *tc)
774 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
775 struct GNUNET_CRYPTO_EccPrivateKey *pk;
777 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
778 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
780 gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
781 GNUNET_CRYPTO_ecc_key_create_stop (gc);
784 GNUNET_assert (GNUNET_OK ==
785 GNUNET_OS_process_wait (gc->gnunet_ecc));
786 GNUNET_OS_process_destroy (gc->gnunet_ecc);
787 gc->gnunet_ecc = NULL;
788 if (NULL == (pk = try_read_key (gc->filename)))
791 gc->cont (gc->cont_cls, NULL, _("gnunet-ecc failed"));
792 GNUNET_CRYPTO_ecc_key_create_stop (gc);
795 gc->cont (gc->cont_cls, pk, NULL);
796 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
797 GNUNET_free (gc->filename);
803 * Return the private ECC key which already existed on disk
804 * (asynchronously) to the caller.
806 * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
807 * @param tc scheduler context (unused)
810 async_return_key (void *cls,
811 const struct GNUNET_SCHEDULER_TaskContext *tc)
813 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
815 gc->cont (gc->cont_cls,
823 * Create a new private key by reading it from a file. If the files
824 * does not exist, create a new key and write it to the file. If the
825 * contents of the file are invalid the old file is deleted and a
826 * fresh key is created.
828 * @param filename name of file to use for storage
829 * @param cont function to call when done (or on errors)
830 * @param cont_cls closure for 'cont'
831 * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
833 struct GNUNET_CRYPTO_EccKeyGenerationContext *
834 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
835 GNUNET_CRYPTO_EccKeyCallback cont,
838 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc;
839 struct GNUNET_CRYPTO_EccPrivateKey *pk;
840 const char *weak_random;
842 if (NULL != (pk = try_read_key (filename)))
844 /* quick happy ending: key already exists! */
845 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
848 gc->cont_cls = cont_cls;
849 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
853 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
854 gc->filename = GNUNET_strdup (filename);
856 gc->cont_cls = cont_cls;
857 gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
861 if (NULL == gc->gnunet_ecc_out)
863 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
864 GNUNET_free (gc->filename);
870 GNUNET_CRYPTO_random_is_weak ())
872 gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
873 GNUNET_OS_INHERIT_STD_ERR,
881 if (NULL == gc->gnunet_ecc)
883 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
884 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
885 GNUNET_free (gc->filename);
889 GNUNET_assert (GNUNET_OK ==
890 GNUNET_DISK_pipe_close_end (gc->gnunet_ecc_out,
891 GNUNET_DISK_PIPE_END_WRITE));
892 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
893 GNUNET_DISK_pipe_handle (gc->gnunet_ecc_out,
894 GNUNET_DISK_PIPE_END_READ),
895 &check_key_generation_completion,
902 * Setup a key file for a peer given the name of the
903 * configuration file (!). This function is used so that
904 * at a later point code can be certain that reading a
905 * key is fast (for example in time-dependent testcases).
907 * @param cfg_name name of the configuration file to use
910 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
912 struct GNUNET_CONFIGURATION_Handle *cfg;
913 struct GNUNET_CRYPTO_EccPrivateKey *pk;
916 cfg = GNUNET_CONFIGURATION_create ();
917 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
919 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
921 pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
923 GNUNET_CRYPTO_ecc_key_free (pk);
926 GNUNET_CONFIGURATION_destroy (cfg);
931 * Convert the data specified in the given purpose argument to an
932 * S-expression suitable for signature operations.
934 * @param purpose data to convert
935 * @return converted s-expression
938 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
940 struct GNUNET_CRYPTO_ShortHashCode hc;
944 GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
945 #define FORMATSTRING "(4:data(5:flags3:raw)(5:value32:01234567890123456789012345678901))"
946 #define FORMATSTRING2 "(4:data(4:hash6:sha25632:01234567890123456789012345678901))"
947 bufSize = strlen (FORMATSTRING) + 1;
951 memcpy (buff, FORMATSTRING, bufSize);
955 ("01234567890123456789012345678901))")
956 - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
957 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
965 * Sign a given block.
967 * @param key private key to use for the signing
968 * @param purpose what to sign (size, purpose)
969 * @param sig where to write the signature
970 * @return GNUNET_SYSERR on error, GNUNET_OK on success
973 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
974 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
975 struct GNUNET_CRYPTO_EccSignature *sig)
982 data = data_to_pkcs1 (purpose);
983 if (0 != (rc = gcry_pk_sign (&result, data, key->sexp)))
985 LOG (GNUNET_ERROR_TYPE_WARNING,
986 _("ECC signing failed at %s:%d: %s\n"), __FILE__,
987 __LINE__, gcry_strerror (rc));
989 gcry_sexp_release (data);
990 ssize = gcry_sexp_sprint (result,
991 GCRYSEXP_FMT_DEFAULT,
993 GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH);
997 return GNUNET_SYSERR;
999 sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
1000 /* padd with zeros */
1001 memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - ssize);
1002 gcry_sexp_release (result);
1010 * @param purpose what is the purpose that the signature should have?
1011 * @param validate block to validate (size, purpose, data)
1012 * @param sig signature that is being validated
1013 * @param publicKey public key of the signer
1014 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1017 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1018 const struct GNUNET_CRYPTO_EccSignaturePurpose
1020 const struct GNUNET_CRYPTO_EccSignature *sig,
1021 const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1025 gcry_sexp_t sigdata;
1031 if (purpose != ntohl (validate->purpose))
1032 return GNUNET_SYSERR; /* purpose mismatch */
1033 size = ntohs (sig->size);
1034 if ( (size < sizeof (uint16_t)) ||
1035 (size > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1036 return GNUNET_SYSERR; /* size out of range */
1037 data = data_to_pkcs1 (validate);
1039 gcry_sexp_sscan (&sigdata, &erroff,
1040 sig->sexpr, size - sizeof (uint16_t)));
1041 if (! (psexp = decode_public_key (publicKey)))
1043 gcry_sexp_release (data);
1044 gcry_sexp_release (sigdata);
1045 return GNUNET_SYSERR;
1047 rc = gcry_pk_verify (sigdata, data, psexp);
1048 gcry_sexp_release (psexp);
1049 gcry_sexp_release (data);
1050 gcry_sexp_release (sigdata);
1053 LOG (GNUNET_ERROR_TYPE_WARNING,
1054 _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1055 __LINE__, gcry_strerror (rc));
1056 return GNUNET_SYSERR;
1062 /* end of crypto_ecc.c */