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 * - adjust encoding length and other parameters
33 #include "gnunet_common.h"
34 #include "gnunet_util_lib.h"
36 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS || 1
38 #define CURVE "NIST P-521"
40 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
42 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
44 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
47 * Log an error message at log-level 'level' that indicates
48 * a failure of the command 'cmd' with the message given
49 * by gcry_strerror(rc).
51 #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);
55 * The private information of an ECC private key.
57 struct GNUNET_CRYPTO_EccPrivateKey
61 * Libgcrypt S-expression for the ECC key.
68 * If target != size, move target bytes to the
69 * end of the size-sized buffer and zero out the
70 * first target-size bytes.
72 * @param buf original buffer
73 * @param size number of bytes in the buffer
74 * @param target target size of the buffer
77 adjust (unsigned char *buf, size_t size, size_t target)
81 memmove (&buf[target - size], buf, size);
82 memset (buf, 0, target - size);
88 * Free memory occupied by ECC key
90 * @param privatekey pointer to the memory to free
93 GNUNET_CRYPTO_ecc_key_free (struct GNUNET_CRYPTO_EccPrivateKey *privatekey)
95 gcry_sexp_release (privatekey->sexp);
96 GNUNET_free (privatekey);
101 * Extract values from an S-expression.
103 * @param array where to store the result(s)
104 * @param sexp S-expression to parse
105 * @param topname top-level name in the S-expression that is of interest
106 * @param elems names of the elements to extract
107 * @return 0 on success
110 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
119 list = gcry_sexp_find_token (sexp, topname, 0);
122 l2 = gcry_sexp_cadr (list);
123 gcry_sexp_release (list);
129 for (s = elems; *s; s++, idx++)
131 l2 = gcry_sexp_find_token (list, s, 1);
134 for (i = 0; i < idx; i++)
136 gcry_free (array[i]);
139 gcry_sexp_release (list);
140 return 3; /* required parameter not found */
142 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
143 gcry_sexp_release (l2);
146 for (i = 0; i < idx; i++)
148 gcry_free (array[i]);
151 gcry_sexp_release (list);
152 return 4; /* required parameter is invalid */
155 gcry_sexp_release (list);
161 * Extract the public key for the given private key.
163 * @param priv the private key
164 * @param pub where to write the public key
167 GNUNET_CRYPTO_ecc_key_get_public (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
168 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
174 rc = key_from_sexp (&skey, priv->sexp, "public-key", "q");
176 rc = key_from_sexp (&skey, priv->sexp, "private-key", "q");
178 rc = key_from_sexp (&skey, priv->sexp, "ecc", "q");
179 GNUNET_assert (0 == rc);
180 pub->size = htons (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
181 size = GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH;
183 gcry_mpi_print (GCRYMPI_FMT_USG, pub->key, size, &size,
185 pub->len = htons (size);
186 adjust (&pub->key[0], size, GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH);
187 gcry_mpi_release (skey);
192 * Convert a public key to a string.
194 * @param pub key to convert
195 * @return string representing 'pub'
198 GNUNET_CRYPTO_ecc_public_key_to_string (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
201 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
205 keylen += 5 - keylen % 5;
207 pubkeybuf = GNUNET_malloc (keylen + 1);
208 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
209 sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded),
214 GNUNET_free (pubkeybuf);
223 * Convert a string representing a public key to a public key.
225 * @param enc encoded public key
226 * @param enclen number of bytes in enc (without 0-terminator)
227 * @param pub where to store the public key
228 * @return GNUNET_OK on success
231 GNUNET_CRYPTO_ecc_public_key_from_string (const char *enc,
233 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
235 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
238 keylen += 5 - keylen % 5;
240 if (enclen != keylen)
241 return GNUNET_SYSERR;
243 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
244 (unsigned char*) pub,
245 sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)))
246 return GNUNET_SYSERR;
247 if ( (ntohs (pub->size) != sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) ||
248 (ntohs (pub->len) > GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH) )
249 return GNUNET_SYSERR;
255 * Convert the given public key from the network format to the
256 * S-expression that can be used by libgcrypt.
258 * @param publicKey public key to decode
259 * @return NULL on error
262 decode_public_key (const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *publicKey)
270 if (ntohs (publicKey->len) > GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH)
275 size = ntohs (publicKey->size);
276 if (0 != (rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG, publicKey->key, size, &size)))
278 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
281 rc = gcry_sexp_build (&result, &erroff, "(public-key(ecc((curve \"" CURVE "\")(q %m)))", q);
282 gcry_mpi_release (q);
285 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
293 * Encode the private key in a format suitable for
294 * storing it into a file.
296 * @param key key to encode
297 * @return encoding of the private key.
298 * The first 4 bytes give the size of the array, as usual.
300 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
301 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key)
303 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *retval;
309 if (0 != gcry_pk_testkey (key->sexp))
315 size = gcry_sexp_sprint (key->sexp,
316 GCRYSEXP_FMT_DEFAULT,
317 &buf[2], sizeof (buf) - sizeof (uint16_t));
323 GNUNET_assert (size < 65536 - sizeof (uint16_t));
324 be = htons ((uint16_t) size + (sizeof (be)));
325 memcpy (buf, &be, sizeof (be));
327 retval = GNUNET_malloc (size);
328 memcpy (retval, buf, size);
334 * Decode the private key from the file-format back
335 * to the "normal", internal format.
337 * @param buf the buffer where the private key data is stored
338 * @param len the length of the data in 'buffer'
339 * @return NULL on error
341 struct GNUNET_CRYPTO_EccPrivateKey *
342 GNUNET_CRYPTO_ecc_decode_key (const char *buf,
345 struct GNUNET_CRYPTO_EccPrivateKey *ret;
351 if (len < sizeof (uint16_t))
353 memcpy (&be, buf, sizeof (be));
354 if (len != ntohs (be))
356 if (0 != (rc = gcry_sexp_sscan (&sexp,
359 len - sizeof (uint16_t))))
361 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
364 if (0 != (rc = gcry_pk_testkey (sexp)))
366 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
369 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
376 * Create a new private key. Caller must free return value.
378 * @return fresh private key
380 static struct GNUNET_CRYPTO_EccPrivateKey *
383 struct GNUNET_CRYPTO_EccPrivateKey *ret;
385 gcry_sexp_t s_keyparam;
388 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
389 "(genkey(ecdsa(curve 10:NIST P-521)))")))
391 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
394 if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
396 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
397 gcry_sexp_release (s_keyparam);
400 gcry_sexp_release (s_keyparam);
402 if (0 != (rc = gcry_pk_testkey (s_key)))
404 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
405 gcry_sexp_release (s_key);
409 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
416 * Try to read the private key from the given file.
418 * @param filename file to read the key from
419 * @return NULL on error
421 static struct GNUNET_CRYPTO_EccPrivateKey *
422 try_read_key (const char *filename)
424 struct GNUNET_CRYPTO_EccPrivateKey *ret;
425 struct GNUNET_DISK_FileHandle *fd;
428 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
431 /* hostkey file exists already, read it! */
432 if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
433 GNUNET_DISK_PERM_NONE)))
435 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
438 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
440 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
441 (void) GNUNET_DISK_file_close (fd);
446 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
451 LOG (GNUNET_ERROR_TYPE_ERROR,
452 _("File `%s' does not contain a valid private key (too long, %llu bytes). Deleting it.\n"),
454 (unsigned long long) fs);
455 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
456 if (0 != UNLINK (filename))
457 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
463 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
464 if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs)))
466 LOG (GNUNET_ERROR_TYPE_ERROR,
467 _("File `%s' does not contain a valid private key (failed decode, %llu bytes). Deleting it.\n"),
469 (unsigned long long) fs);
470 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
471 if (0 != UNLINK (filename))
472 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
476 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
482 * Wait for a short time (we're trying to lock a file or want
483 * to give another process a shot at finishing a disk write, etc.).
484 * Sleeps for 100ms (as that should be long enough for virtually all
485 * modern systems to context switch and allow another process to do
491 struct GNUNET_TIME_Relative timeout;
493 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
494 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
499 * Create a new private key by reading it from a file. If the
500 * files does not exist, create a new key and write it to the
501 * file. Caller must free return value. Note that this function
502 * can not guarantee that another process might not be trying
503 * the same operation on the same file at the same time.
504 * If the contents of the file
505 * are invalid the old file is deleted and a fresh key is
508 * @return new private key, NULL on error (for example,
511 struct GNUNET_CRYPTO_EccPrivateKey *
512 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
514 struct GNUNET_CRYPTO_EccPrivateKey *ret;
515 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
517 struct GNUNET_DISK_FileHandle *fd;
521 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
522 struct GNUNET_PeerIdentity pid;
524 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
526 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
528 fd = GNUNET_DISK_file_open (filename,
529 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
530 | GNUNET_DISK_OPEN_FAILIFEXISTS,
531 GNUNET_DISK_PERM_USER_READ |
532 GNUNET_DISK_PERM_USER_WRITE);
537 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
539 /* must exist but not be accessible, fail for good! */
540 if (0 != ACCESS (filename, R_OK))
541 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
543 GNUNET_break (0); /* what is going on!? */
548 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
554 GNUNET_DISK_file_lock (fd, 0,
555 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
562 LOG (GNUNET_ERROR_TYPE_ERROR,
563 _("Could not acquire lock on file `%s': %s...\n"), filename,
567 LOG (GNUNET_ERROR_TYPE_INFO,
568 _("Creating a new private key. This may take a while.\n"));
569 ret = ecc_key_create ();
570 GNUNET_assert (ret != NULL);
571 enc = GNUNET_CRYPTO_ecc_encode_key (ret);
572 GNUNET_assert (enc != NULL);
573 GNUNET_assert (ntohs (enc->size) ==
574 GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
577 GNUNET_DISK_file_sync (fd);
579 GNUNET_DISK_file_unlock (fd, 0,
580 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
581 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
582 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
583 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
584 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
585 LOG (GNUNET_ERROR_TYPE_INFO,
586 _("I am host `%s'. Stored new private key in `%s'.\n"),
587 GNUNET_i2s (&pid), filename);
590 /* hostkey file exists already, read it! */
591 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
592 GNUNET_DISK_PERM_NONE);
595 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
602 GNUNET_DISK_file_lock (fd, 0,
603 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
609 LOG (GNUNET_ERROR_TYPE_ERROR,
610 _("Could not acquire lock on file `%s': %s...\n"), filename,
612 LOG (GNUNET_ERROR_TYPE_ERROR,
614 ("This may be ok if someone is currently generating a hostkey.\n"));
619 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
621 /* eh, what!? File we opened is now gone!? */
622 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
624 GNUNET_DISK_file_unlock (fd, 0,
625 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
626 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
627 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
631 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
633 if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
635 /* maybe we got the read lock before the hostkey generating
636 * process had a chance to get the write lock; give it up! */
638 GNUNET_DISK_file_unlock (fd, 0,
639 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
640 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
643 LOG (GNUNET_ERROR_TYPE_ERROR,
645 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
646 filename, (unsigned int) fs,
647 (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
648 LOG (GNUNET_ERROR_TYPE_ERROR,
650 ("This may be ok if someone is currently generating a hostkey.\n"));
652 short_wait (); /* wait a bit longer! */
657 enc = GNUNET_malloc (fs);
658 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
659 len = ntohs (enc->size);
662 (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len))))
664 LOG (GNUNET_ERROR_TYPE_ERROR,
665 _("File `%s' does not contain a valid private key. Deleting it.\n"),
667 if (0 != UNLINK (filename))
669 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
674 GNUNET_DISK_file_unlock (fd, 0,
675 sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
676 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
677 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
680 GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
681 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
682 LOG (GNUNET_ERROR_TYPE_INFO,
683 _("I am host `%s'. Read private key from `%s'.\n"), GNUNET_i2s (&pid),
691 * Handle to cancel private key generation and state for the
692 * key generation operation.
694 struct GNUNET_CRYPTO_EccKeyGenerationContext
698 * Continuation to call upon completion.
700 GNUNET_CRYPTO_EccKeyCallback cont;
703 * Closure for 'cont'.
713 * Handle to the helper process which does the key generation.
715 struct GNUNET_OS_Process *gnunet_ecc;
718 * Handle to 'stdout' of gnunet-ecc. We 'read' on stdout to detect
719 * process termination (instead of messing with SIGCHLD).
721 struct GNUNET_DISK_PipeHandle *gnunet_ecc_out;
724 * Location where we store the private key if it already existed.
725 * (if this is used, 'filename', 'gnunet_ecc' and 'gnunet_ecc_out' will
728 struct GNUNET_CRYPTO_EccPrivateKey *pk;
731 * Task reading from 'gnunet_ecc_out' to wait for process termination.
733 GNUNET_SCHEDULER_TaskIdentifier read_task;
739 * Abort ECC key generation.
741 * @param gc key generation context to abort
744 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc)
746 if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
748 GNUNET_SCHEDULER_cancel (gc->read_task);
749 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
751 if (NULL != gc->gnunet_ecc)
753 (void) GNUNET_OS_process_kill (gc->gnunet_ecc, SIGKILL);
754 GNUNET_break (GNUNET_OK ==
755 GNUNET_OS_process_wait (gc->gnunet_ecc));
756 GNUNET_OS_process_destroy (gc->gnunet_ecc);
757 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
760 if (NULL != gc->filename)
762 if (0 != UNLINK (gc->filename))
763 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
764 GNUNET_free (gc->filename);
767 GNUNET_CRYPTO_ecc_key_free (gc->pk);
773 * Task called upon shutdown or process termination of 'gnunet-ecc' during
774 * ECC key generation. Check where we are and perform the appropriate
777 * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
778 * @param tc scheduler context
781 check_key_generation_completion (void *cls,
782 const struct GNUNET_SCHEDULER_TaskContext *tc)
784 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
785 struct GNUNET_CRYPTO_EccPrivateKey *pk;
787 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
788 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
790 gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
791 GNUNET_CRYPTO_ecc_key_create_stop (gc);
794 GNUNET_assert (GNUNET_OK ==
795 GNUNET_OS_process_wait (gc->gnunet_ecc));
796 GNUNET_OS_process_destroy (gc->gnunet_ecc);
797 gc->gnunet_ecc = NULL;
798 if (NULL == (pk = try_read_key (gc->filename)))
801 gc->cont (gc->cont_cls, NULL, _("gnunet-ecc failed"));
802 GNUNET_CRYPTO_ecc_key_create_stop (gc);
805 gc->cont (gc->cont_cls, pk, NULL);
806 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
807 GNUNET_free (gc->filename);
813 * Return the private ECC key which already existed on disk
814 * (asynchronously) to the caller.
816 * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
817 * @param tc scheduler context (unused)
820 async_return_key (void *cls,
821 const struct GNUNET_SCHEDULER_TaskContext *tc)
823 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
825 gc->cont (gc->cont_cls,
833 * Create a new private key by reading it from a file. If the files
834 * does not exist, create a new key and write it to the file. If the
835 * contents of the file are invalid the old file is deleted and a
836 * fresh key is created.
838 * @param filename name of file to use for storage
839 * @param cont function to call when done (or on errors)
840 * @param cont_cls closure for 'cont'
841 * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
843 struct GNUNET_CRYPTO_EccKeyGenerationContext *
844 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
845 GNUNET_CRYPTO_EccKeyCallback cont,
848 struct GNUNET_CRYPTO_EccKeyGenerationContext *gc;
849 struct GNUNET_CRYPTO_EccPrivateKey *pk;
850 const char *weak_random;
852 if (NULL != (pk = try_read_key (filename)))
854 /* quick happy ending: key already exists! */
855 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
858 gc->cont_cls = cont_cls;
859 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
863 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
864 gc->filename = GNUNET_strdup (filename);
866 gc->cont_cls = cont_cls;
867 gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
871 if (NULL == gc->gnunet_ecc_out)
873 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
874 GNUNET_free (gc->filename);
880 GNUNET_CRYPTO_random_is_weak ())
882 gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
883 GNUNET_OS_INHERIT_STD_ERR,
891 if (NULL == gc->gnunet_ecc)
893 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
894 GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
895 GNUNET_free (gc->filename);
899 GNUNET_assert (GNUNET_OK ==
900 GNUNET_DISK_pipe_close_end (gc->gnunet_ecc_out,
901 GNUNET_DISK_PIPE_END_WRITE));
902 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
903 GNUNET_DISK_pipe_handle (gc->gnunet_ecc_out,
904 GNUNET_DISK_PIPE_END_READ),
905 &check_key_generation_completion,
912 * Setup a hostkey file for a peer given the name of the
913 * configuration file (!). This function is used so that
914 * at a later point code can be certain that reading a
915 * hostkey is fast (for example in time-dependent testcases).
917 * @param cfg_name name of the configuration file to use
920 GNUNET_CRYPTO_ecc_setup_hostkey (const char *cfg_name)
922 struct GNUNET_CONFIGURATION_Handle *cfg;
923 struct GNUNET_CRYPTO_EccPrivateKey *pk;
926 cfg = GNUNET_CONFIGURATION_create ();
927 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
929 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
931 pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
933 GNUNET_CRYPTO_ecc_key_free (pk);
936 GNUNET_CONFIGURATION_destroy (cfg);
941 * Convert the data specified in the given purpose argument to an
942 * S-expression suitable for signature operations.
944 * @param purpose data to convert
945 * @return converted s-expression
948 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
950 struct GNUNET_HashCode hc;
954 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
955 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
956 bufSize = strlen (FORMATSTRING) + 1;
960 memcpy (buff, FORMATSTRING, bufSize);
964 ("0123456789012345678901234567890123456789012345678901234567890123))")
965 - 1], &hc, sizeof (struct GNUNET_HashCode));
966 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
974 * Sign a given block.
976 * @param key private key to use for the signing
977 * @param purpose what to sign (size, purpose)
978 * @param sig where to write the signature
979 * @return GNUNET_SYSERR on error, GNUNET_OK on success
982 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
983 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
984 struct GNUNET_CRYPTO_EccSignature *sig)
990 data = data_to_pkcs1 (purpose);
991 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
992 gcry_sexp_release (data);
993 ssize = gcry_sexp_sprint (result,
994 GCRYSEXP_FMT_DEFAULT,
996 GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH);
1000 return GNUNET_SYSERR;
1002 sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
1003 /* padd with zeros */
1004 memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH - ssize);
1005 gcry_sexp_release (result);
1013 * @param purpose what is the purpose that the signature should have?
1014 * @param validate block to validate (size, purpose, data)
1015 * @param sig signature that is being validated
1016 * @param publicKey public key of the signer
1017 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1020 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1021 const struct GNUNET_CRYPTO_EccSignaturePurpose
1023 const struct GNUNET_CRYPTO_EccSignature *sig,
1024 const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1028 gcry_sexp_t sigdata;
1034 if (purpose != ntohl (validate->purpose))
1035 return GNUNET_SYSERR; /* purpose mismatch */
1036 size = ntohs (sig->size);
1037 if ( (size < sizeof (uint16_t)) ||
1038 (size > GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1039 return GNUNET_SYSERR; /* size out of range */
1040 data = data_to_pkcs1 (validate);
1042 gcry_sexp_sscan (&sigdata, &erroff,
1043 sig->sexpr, size - sizeof (uint16_t)));
1044 if (! (psexp = decode_public_key (publicKey)))
1046 gcry_sexp_release (data);
1047 gcry_sexp_release (sigdata);
1048 return GNUNET_SYSERR;
1050 rc = gcry_pk_verify (sigdata, data, psexp);
1051 gcry_sexp_release (psexp);
1052 gcry_sexp_release (data);
1053 gcry_sexp_release (sigdata);
1056 LOG (GNUNET_ERROR_TYPE_WARNING,
1057 _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1058 __LINE__, gcry_strerror (rc));
1059 return GNUNET_SYSERR;
1065 /* end of crypto_ecc.c */