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 3, 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_util_lib.h"
30 #define EXTRA_CHECKS 0
33 * Name of the curve we are using. Note that we have hard-coded
34 * structs that use 256 bits, so using a bigger curve will require
35 * changes that break stuff badly. The name of the curve given here
36 * must be agreed by all peers and be supported by libgcrypt.
38 #define CURVE "Ed25519"
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 * Extract values from an S-expression.
57 * @param array where to store the result(s)
58 * @param sexp S-expression to parse
59 * @param topname top-level name in the S-expression that is of interest
60 * @param elems names of the elements to extract
61 * @return 0 on success
64 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
73 list = gcry_sexp_find_token (sexp, topname, 0);
76 l2 = gcry_sexp_cadr (list);
77 gcry_sexp_release (list);
83 for (s = elems; *s; s++, idx++)
85 l2 = gcry_sexp_find_token (list, s, 1);
88 for (i = 0; i < idx; i++)
93 gcry_sexp_release (list);
94 return 3; /* required parameter not found */
96 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
97 gcry_sexp_release (l2);
100 for (i = 0; i < idx; i++)
102 gcry_free (array[i]);
105 gcry_sexp_release (list);
106 return 4; /* required parameter is invalid */
109 gcry_sexp_release (list);
115 * Convert the given private key from the network format to the
116 * S-expression that can be used by libgcrypt.
118 * @param priv private key to decode
119 * @return NULL on error
122 decode_private_ecdsa_key (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv)
127 rc = gcry_sexp_build (&result, NULL,
128 "(private-key(ecc(curve \"" CURVE "\")"
130 (int)sizeof (priv->d), priv->d);
133 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
137 if (0 != (rc = gcry_pk_testkey (result)))
139 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
148 * Convert the given private key from the network format to the
149 * S-expression that can be used by libgcrypt.
151 * @param priv private key to decode
152 * @return NULL on error
155 decode_private_eddsa_key (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv)
160 rc = gcry_sexp_build (&result, NULL,
161 "(private-key(ecc(curve \"" CURVE "\")"
162 "(flags eddsa)(d %b)))",
163 (int)sizeof (priv->d), priv->d);
166 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
170 if (0 != (rc = gcry_pk_testkey (result)))
172 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
181 * Convert the given private key from the network format to the
182 * S-expression that can be used by libgcrypt.
184 * @param priv private key to decode
185 * @return NULL on error
188 decode_private_ecdhe_key (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv)
193 rc = gcry_sexp_build (&result, NULL,
194 "(private-key(ecc(curve \"" CURVE "\")"
196 (int)sizeof (priv->d), priv->d);
199 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
203 if (0 != (rc = gcry_pk_testkey (result)))
205 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
214 * Extract the public key for the given private key.
216 * @param priv the private key
217 * @param pub where to write the public key
220 GNUNET_CRYPTO_ecdsa_key_get_public (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
221 struct GNUNET_CRYPTO_EcdsaPublicKey *pub)
227 sexp = decode_private_ecdsa_key (priv);
228 GNUNET_assert (NULL != sexp);
229 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL));
230 gcry_sexp_release (sexp);
231 q = gcry_mpi_ec_get_mpi ("q@eddsa", ctx, 0);
233 GNUNET_CRYPTO_mpi_print_unsigned (pub->q_y, sizeof (pub->q_y), q);
234 gcry_mpi_release (q);
235 gcry_ctx_release (ctx);
240 * Extract the public key for the given private key.
242 * @param priv the private key
243 * @param pub where to write the public key
246 GNUNET_CRYPTO_eddsa_key_get_public (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
247 struct GNUNET_CRYPTO_EddsaPublicKey *pub)
253 sexp = decode_private_eddsa_key (priv);
254 GNUNET_assert (NULL != sexp);
255 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL));
256 gcry_sexp_release (sexp);
257 q = gcry_mpi_ec_get_mpi ("q@eddsa", ctx, 0);
259 GNUNET_CRYPTO_mpi_print_unsigned (pub->q_y, sizeof (pub->q_y), q);
260 gcry_mpi_release (q);
261 gcry_ctx_release (ctx);
266 * Extract the public key for the given private key.
268 * @param priv the private key
269 * @param pub where to write the public key
272 GNUNET_CRYPTO_ecdhe_key_get_public (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
273 struct GNUNET_CRYPTO_EcdhePublicKey *pub)
279 sexp = decode_private_ecdhe_key (priv);
280 GNUNET_assert (NULL != sexp);
281 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL));
282 gcry_sexp_release (sexp);
283 q = gcry_mpi_ec_get_mpi ("q@eddsa", ctx, 0);
285 GNUNET_CRYPTO_mpi_print_unsigned (pub->q_y, sizeof (pub->q_y), q);
286 gcry_mpi_release (q);
287 gcry_ctx_release (ctx);
292 * Convert a public key to a string.
294 * @param pub key to convert
295 * @return string representing @a pub
298 GNUNET_CRYPTO_ecdsa_public_key_to_string (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub)
301 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)) * 8;
305 keylen += 5 - keylen % 5;
307 pubkeybuf = GNUNET_malloc (keylen + 1);
308 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
309 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
314 GNUNET_free (pubkeybuf);
323 * Convert a public key to a string.
325 * @param pub key to convert
326 * @return string representing @a pub
329 GNUNET_CRYPTO_eddsa_public_key_to_string (const struct GNUNET_CRYPTO_EddsaPublicKey *pub)
332 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)) * 8;
336 keylen += 5 - keylen % 5;
338 pubkeybuf = GNUNET_malloc (keylen + 1);
339 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
340 sizeof (struct GNUNET_CRYPTO_EddsaPublicKey),
345 GNUNET_free (pubkeybuf);
354 * Convert a string representing a public key to a public key.
356 * @param enc encoded public key
357 * @param enclen number of bytes in @a enc (without 0-terminator)
358 * @param pub where to store the public key
359 * @return #GNUNET_OK on success
362 GNUNET_CRYPTO_ecdsa_public_key_from_string (const char *enc,
364 struct GNUNET_CRYPTO_EcdsaPublicKey *pub)
366 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)) * 8;
369 keylen += 5 - keylen % 5;
371 if (enclen != keylen)
372 return GNUNET_SYSERR;
374 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
376 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)))
377 return GNUNET_SYSERR;
383 * Convert a string representing a public key to a public key.
385 * @param enc encoded public key
386 * @param enclen number of bytes in @a enc (without 0-terminator)
387 * @param pub where to store the public key
388 * @return #GNUNET_OK on success
391 GNUNET_CRYPTO_eddsa_public_key_from_string (const char *enc,
393 struct GNUNET_CRYPTO_EddsaPublicKey *pub)
395 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)) * 8;
398 keylen += 5 - keylen % 5;
400 if (enclen != keylen)
401 return GNUNET_SYSERR;
403 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
405 sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)))
406 return GNUNET_SYSERR;
413 * Clear memory that was used to store a private key.
415 * @param pk location of the key
418 GNUNET_CRYPTO_ecdhe_key_clear (struct GNUNET_CRYPTO_EcdhePrivateKey *pk)
420 memset (pk, 0, sizeof (struct GNUNET_CRYPTO_EcdhePrivateKey));
426 * Clear memory that was used to store a private key.
428 * @param pk location of the key
431 GNUNET_CRYPTO_ecdsa_key_clear (struct GNUNET_CRYPTO_EcdsaPrivateKey *pk)
433 memset (pk, 0, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
439 * Clear memory that was used to store a private key.
441 * @param pk location of the key
444 GNUNET_CRYPTO_eddsa_key_clear (struct GNUNET_CRYPTO_EddsaPrivateKey *pk)
446 memset (pk, 0, sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey));
451 * Create a new private key. Caller must free return value.
453 * @return fresh private key
455 struct GNUNET_CRYPTO_EcdhePrivateKey *
456 GNUNET_CRYPTO_ecdhe_key_create ()
458 struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
459 gcry_sexp_t priv_sexp;
460 gcry_sexp_t s_keyparam;
464 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
465 "(genkey(ecc(curve \"" CURVE "\")"
468 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
471 if (0 != (rc = gcry_pk_genkey (&priv_sexp, s_keyparam)))
473 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
474 gcry_sexp_release (s_keyparam);
477 gcry_sexp_release (s_keyparam);
479 if (0 != (rc = gcry_pk_testkey (priv_sexp)))
481 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
482 gcry_sexp_release (priv_sexp);
486 if (0 != (rc = key_from_sexp (&d, priv_sexp, "private-key", "d")))
488 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
489 gcry_sexp_release (priv_sexp);
492 gcry_sexp_release (priv_sexp);
493 priv = GNUNET_new (struct GNUNET_CRYPTO_EcdhePrivateKey);
494 GNUNET_CRYPTO_mpi_print_unsigned (priv->d, sizeof (priv->d), d);
495 gcry_mpi_release (d);
501 * Create a new private key. Caller must free return value.
503 * @return fresh private key
505 struct GNUNET_CRYPTO_EcdsaPrivateKey *
506 GNUNET_CRYPTO_ecdsa_key_create ()
508 struct GNUNET_CRYPTO_EcdsaPrivateKey *priv;
509 gcry_sexp_t priv_sexp;
510 gcry_sexp_t s_keyparam;
514 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
515 "(genkey(ecc(curve \"" CURVE "\")"
518 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
521 if (0 != (rc = gcry_pk_genkey (&priv_sexp, s_keyparam)))
523 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
524 gcry_sexp_release (s_keyparam);
527 gcry_sexp_release (s_keyparam);
529 if (0 != (rc = gcry_pk_testkey (priv_sexp)))
531 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
532 gcry_sexp_release (priv_sexp);
536 if (0 != (rc = key_from_sexp (&d, priv_sexp, "private-key", "d")))
538 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
539 gcry_sexp_release (priv_sexp);
542 gcry_sexp_release (priv_sexp);
543 priv = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPrivateKey);
544 GNUNET_CRYPTO_mpi_print_unsigned (priv->d, sizeof (priv->d), d);
545 gcry_mpi_release (d);
550 * Create a new private key. Caller must free return value.
552 * @return fresh private key
554 struct GNUNET_CRYPTO_EddsaPrivateKey *
555 GNUNET_CRYPTO_eddsa_key_create ()
557 struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
558 gcry_sexp_t priv_sexp;
559 gcry_sexp_t s_keyparam;
563 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
564 "(genkey(ecc(curve \"" CURVE "\")"
567 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
570 if (0 != (rc = gcry_pk_genkey (&priv_sexp, s_keyparam)))
572 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
573 gcry_sexp_release (s_keyparam);
576 gcry_sexp_release (s_keyparam);
578 if (0 != (rc = gcry_pk_testkey (priv_sexp)))
580 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
581 gcry_sexp_release (priv_sexp);
585 if (0 != (rc = key_from_sexp (&d, priv_sexp, "private-key", "d")))
587 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
588 gcry_sexp_release (priv_sexp);
591 gcry_sexp_release (priv_sexp);
592 priv = GNUNET_new (struct GNUNET_CRYPTO_EddsaPrivateKey);
593 GNUNET_CRYPTO_mpi_print_unsigned (priv->d, sizeof (priv->d), d);
594 gcry_mpi_release (d);
600 * Get the shared private key we use for anonymous users.
602 * @return "anonymous" private key
604 const struct GNUNET_CRYPTO_EcdsaPrivateKey *
605 GNUNET_CRYPTO_ecdsa_key_get_anonymous ()
608 * 'anonymous' pseudonym (global static, d=1, public key = G
611 static struct GNUNET_CRYPTO_EcdsaPrivateKey anonymous;
616 GNUNET_CRYPTO_mpi_print_unsigned (anonymous.d,
617 sizeof (anonymous.d),
625 * Wait for a short time (we're trying to lock a file or want
626 * to give another process a shot at finishing a disk write, etc.).
627 * Sleeps for 100ms (as that should be long enough for virtually all
628 * modern systems to context switch and allow another process to do
634 struct GNUNET_TIME_Relative timeout;
636 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
637 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
642 * Create a new private key by reading it from a file. If the
643 * files does not exist, create a new key and write it to the
644 * file. Caller must free return value. Note that this function
645 * can not guarantee that another process might not be trying
646 * the same operation on the same file at the same time.
647 * If the contents of the file
648 * are invalid the old file is deleted and a fresh key is
651 * @param filename name of file to use to store the key
652 * @return new private key, NULL on error (for example,
655 struct GNUNET_CRYPTO_EddsaPrivateKey *
656 GNUNET_CRYPTO_eddsa_key_create_from_file (const char *filename)
658 struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
659 struct GNUNET_DISK_FileHandle *fd;
664 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
666 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
668 fd = GNUNET_DISK_file_open (filename,
669 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
670 | GNUNET_DISK_OPEN_FAILIFEXISTS,
671 GNUNET_DISK_PERM_USER_READ |
672 GNUNET_DISK_PERM_USER_WRITE);
677 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
679 /* must exist but not be accessible, fail for good! */
680 if (0 != ACCESS (filename, R_OK))
681 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
683 GNUNET_break (0); /* what is going on!? */
688 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
693 GNUNET_DISK_file_lock (fd, 0,
694 sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey),
701 LOG (GNUNET_ERROR_TYPE_ERROR,
702 _("Could not acquire lock on file `%s': %s...\n"), filename,
706 LOG (GNUNET_ERROR_TYPE_INFO,
707 _("Creating a new private key. This may take a while.\n"));
708 priv = GNUNET_CRYPTO_eddsa_key_create ();
709 GNUNET_assert (NULL != priv);
710 GNUNET_assert (sizeof (*priv) ==
711 GNUNET_DISK_file_write (fd, priv, sizeof (*priv)));
712 GNUNET_DISK_file_sync (fd);
714 GNUNET_DISK_file_unlock (fd, 0,
715 sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)))
716 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
717 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
720 /* key file exists already, read it! */
721 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
722 GNUNET_DISK_PERM_NONE);
725 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
732 GNUNET_DISK_file_lock (fd, 0,
733 sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey),
739 LOG (GNUNET_ERROR_TYPE_ERROR,
740 _("Could not acquire lock on file `%s': %s...\n"), filename,
742 LOG (GNUNET_ERROR_TYPE_ERROR,
744 ("This may be ok if someone is currently generating a private key.\n"));
749 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
751 /* eh, what!? File we opened is now gone!? */
752 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
754 GNUNET_DISK_file_unlock (fd, 0,
755 sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)))
756 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
757 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
761 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
763 if (fs < sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey))
765 /* maybe we got the read lock before the key generating
766 * process had a chance to get the write lock; give it up! */
768 GNUNET_DISK_file_unlock (fd, 0,
769 sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)))
770 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
773 LOG (GNUNET_ERROR_TYPE_ERROR,
774 _("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
775 filename, (unsigned int) fs,
776 (unsigned int) sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey));
777 LOG (GNUNET_ERROR_TYPE_ERROR,
778 _("This may be ok if someone is currently generating a key.\n"));
780 short_wait (); /* wait a bit longer! */
785 fs = sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey);
786 priv = GNUNET_malloc (fs);
787 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, priv, fs));
789 GNUNET_DISK_file_unlock (fd, 0,
790 sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)))
791 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
792 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
798 * Create a new private key by reading it from a file. If the
799 * files does not exist, create a new key and write it to the
800 * file. Caller must free return value. Note that this function
801 * can not guarantee that another process might not be trying
802 * the same operation on the same file at the same time.
803 * If the contents of the file
804 * are invalid the old file is deleted and a fresh key is
807 * @param filename name of file to use to store the key
808 * @return new private key, NULL on error (for example,
811 struct GNUNET_CRYPTO_EcdsaPrivateKey *
812 GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename)
814 struct GNUNET_CRYPTO_EcdsaPrivateKey *priv;
815 struct GNUNET_DISK_FileHandle *fd;
820 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
822 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
824 fd = GNUNET_DISK_file_open (filename,
825 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
826 | GNUNET_DISK_OPEN_FAILIFEXISTS,
827 GNUNET_DISK_PERM_USER_READ |
828 GNUNET_DISK_PERM_USER_WRITE);
833 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
835 /* must exist but not be accessible, fail for good! */
836 if (0 != ACCESS (filename, R_OK))
837 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
839 GNUNET_break (0); /* what is going on!? */
844 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
849 GNUNET_DISK_file_lock (fd, 0,
850 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
857 LOG (GNUNET_ERROR_TYPE_ERROR,
858 _("Could not acquire lock on file `%s': %s...\n"), filename,
862 LOG (GNUNET_ERROR_TYPE_INFO,
863 _("Creating a new private key. This may take a while.\n"));
864 priv = GNUNET_CRYPTO_ecdsa_key_create ();
865 GNUNET_assert (NULL != priv);
866 GNUNET_assert (sizeof (*priv) ==
867 GNUNET_DISK_file_write (fd, priv, sizeof (*priv)));
868 GNUNET_DISK_file_sync (fd);
870 GNUNET_DISK_file_unlock (fd, 0,
871 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
872 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
873 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
876 /* key file exists already, read it! */
877 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
878 GNUNET_DISK_PERM_NONE);
881 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
888 GNUNET_DISK_file_lock (fd, 0,
889 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
895 LOG (GNUNET_ERROR_TYPE_ERROR,
896 _("Could not acquire lock on file `%s': %s...\n"), filename,
898 LOG (GNUNET_ERROR_TYPE_ERROR,
900 ("This may be ok if someone is currently generating a private key.\n"));
905 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
907 /* eh, what!? File we opened is now gone!? */
908 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
910 GNUNET_DISK_file_unlock (fd, 0,
911 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
912 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
913 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
917 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
919 if (fs < sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))
921 /* maybe we got the read lock before the key generating
922 * process had a chance to get the write lock; give it up! */
924 GNUNET_DISK_file_unlock (fd, 0,
925 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
926 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
929 LOG (GNUNET_ERROR_TYPE_ERROR,
930 _("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
931 filename, (unsigned int) fs,
932 (unsigned int) sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey));
933 LOG (GNUNET_ERROR_TYPE_ERROR,
934 _("This may be ok if someone is currently generating a key.\n"));
936 short_wait (); /* wait a bit longer! */
941 fs = sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey);
942 priv = GNUNET_malloc (fs);
943 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, priv, fs));
945 GNUNET_DISK_file_unlock (fd, 0,
946 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
947 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
948 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
954 * Create a new private key by reading our peer's key from
955 * the file specified in the configuration.
957 * @param cfg the configuration to use
958 * @return new private key, NULL on error (for example,
961 struct GNUNET_CRYPTO_EddsaPrivateKey *
962 GNUNET_CRYPTO_eddsa_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
964 struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
968 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
970 priv = GNUNET_CRYPTO_eddsa_key_create_from_file (fn);
977 * Setup a key file for a peer given the name of the
978 * configuration file (!). This function is used so that
979 * at a later point code can be certain that reading a
980 * key is fast (for example in time-dependent testcases).
982 * @param cfg_name name of the configuration file to use
985 GNUNET_CRYPTO_eddsa_setup_key (const char *cfg_name)
987 struct GNUNET_CONFIGURATION_Handle *cfg;
988 struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
990 cfg = GNUNET_CONFIGURATION_create ();
991 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
992 priv = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
995 GNUNET_CONFIGURATION_destroy (cfg);
1000 * Retrieve the identity of the host's peer.
1002 * @param cfg configuration to use
1003 * @param dst pointer to where to write the peer identity
1004 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the identity
1005 * could not be retrieved
1008 GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
1009 struct GNUNET_PeerIdentity *dst)
1011 struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
1013 if (NULL == (priv = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg)))
1015 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1016 _("Could not load peer's private key\n"));
1017 return GNUNET_SYSERR;
1019 GNUNET_CRYPTO_eddsa_key_get_public (priv, &dst->public_key);
1026 * Compare two Peer Identities.
1028 * @param first first peer identity
1029 * @param second second peer identity
1030 * @return bigger than 0 if first > second,
1031 * 0 if they are the same
1032 * smaller than 0 if second > first
1035 GNUNET_CRYPTO_cmp_peer_identity (const struct GNUNET_PeerIdentity *first,
1036 const struct GNUNET_PeerIdentity *second)
1038 return memcmp (first, second, sizeof (struct GNUNET_PeerIdentity));
1043 * Convert the data specified in the given purpose argument to an
1044 * S-expression suitable for signature operations.
1046 * @param purpose data to convert
1047 * @return converted s-expression
1050 data_to_eddsa_value (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
1052 struct GNUNET_HashCode hc;
1056 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1057 if (0 != (rc = gcry_sexp_build (&data, NULL,
1058 "(data(flags eddsa)(hash-algo %s)(value %b))",
1060 (int)sizeof (hc), &hc)))
1062 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
1070 * Convert the data specified in the given purpose argument to an
1071 * S-expression suitable for signature operations.
1073 * @param purpose data to convert
1074 * @return converted s-expression
1077 data_to_ecdsa_value (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
1079 struct GNUNET_HashCode hc;
1083 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1084 if (0 != (rc = gcry_sexp_build (&data, NULL,
1085 "(data(flags rfc6979)(hash %s %b))",
1087 (int)sizeof (hc), &hc)))
1089 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
1097 * Sign a given block.
1099 * @param priv private key to use for the signing
1100 * @param purpose what to sign (size, purpose)
1101 * @param sig where to write the signature
1102 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1105 GNUNET_CRYPTO_ecdsa_sign (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1106 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1107 struct GNUNET_CRYPTO_EcdsaSignature *sig)
1109 gcry_sexp_t priv_sexp;
1110 gcry_sexp_t sig_sexp;
1115 priv_sexp = decode_private_ecdsa_key (priv);
1116 data = data_to_ecdsa_value (purpose);
1117 if (0 != (rc = gcry_pk_sign (&sig_sexp, data, priv_sexp)))
1119 LOG (GNUNET_ERROR_TYPE_WARNING,
1120 _("ECC signing failed at %s:%d: %s\n"), __FILE__,
1121 __LINE__, gcry_strerror (rc));
1122 gcry_sexp_release (data);
1123 gcry_sexp_release (priv_sexp);
1124 return GNUNET_SYSERR;
1126 gcry_sexp_release (priv_sexp);
1127 gcry_sexp_release (data);
1129 /* extract 'r' and 's' values from sexpression 'sig_sexp' and store in
1131 if (0 != (rc = key_from_sexp (rs, sig_sexp, "sig-val", "rs")))
1134 gcry_sexp_release (sig_sexp);
1135 return GNUNET_SYSERR;
1137 gcry_sexp_release (sig_sexp);
1138 GNUNET_CRYPTO_mpi_print_unsigned (sig->r, sizeof (sig->r), rs[0]);
1139 GNUNET_CRYPTO_mpi_print_unsigned (sig->s, sizeof (sig->s), rs[1]);
1140 gcry_mpi_release (rs[0]);
1141 gcry_mpi_release (rs[1]);
1147 * Sign a given block.
1149 * @param priv private key to use for the signing
1150 * @param purpose what to sign (size, purpose)
1151 * @param sig where to write the signature
1152 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1155 GNUNET_CRYPTO_eddsa_sign (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1156 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1157 struct GNUNET_CRYPTO_EddsaSignature *sig)
1159 gcry_sexp_t priv_sexp;
1160 gcry_sexp_t sig_sexp;
1165 priv_sexp = decode_private_eddsa_key (priv);
1166 data = data_to_eddsa_value (purpose);
1167 if (0 != (rc = gcry_pk_sign (&sig_sexp, data, priv_sexp)))
1169 LOG (GNUNET_ERROR_TYPE_WARNING,
1170 _("EdDSA signing failed at %s:%d: %s\n"), __FILE__,
1171 __LINE__, gcry_strerror (rc));
1172 gcry_sexp_release (data);
1173 gcry_sexp_release (priv_sexp);
1174 return GNUNET_SYSERR;
1176 gcry_sexp_release (priv_sexp);
1177 gcry_sexp_release (data);
1179 /* extract 'r' and 's' values from sexpression 'sig_sexp' and store in
1181 if (0 != (rc = key_from_sexp (rs, sig_sexp, "sig-val", "rs")))
1184 gcry_sexp_release (sig_sexp);
1185 return GNUNET_SYSERR;
1187 gcry_sexp_release (sig_sexp);
1188 GNUNET_CRYPTO_mpi_print_unsigned (sig->r, sizeof (sig->r), rs[0]);
1189 GNUNET_CRYPTO_mpi_print_unsigned (sig->s, sizeof (sig->s), rs[1]);
1190 gcry_mpi_release (rs[0]);
1191 gcry_mpi_release (rs[1]);
1199 * @param purpose what is the purpose that the signature should have?
1200 * @param validate block to validate (size, purpose, data)
1201 * @param sig signature that is being validated
1202 * @param pub public key of the signer
1203 * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1206 GNUNET_CRYPTO_ecdsa_verify (uint32_t purpose,
1207 const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1208 const struct GNUNET_CRYPTO_EcdsaSignature *sig,
1209 const struct GNUNET_CRYPTO_EcdsaPublicKey *pub)
1212 gcry_sexp_t sig_sexpr;
1213 gcry_sexp_t pub_sexpr;
1216 if (purpose != ntohl (validate->purpose))
1217 return GNUNET_SYSERR; /* purpose mismatch */
1219 /* build s-expression for signature */
1220 if (0 != (rc = gcry_sexp_build (&sig_sexpr, NULL,
1221 "(sig-val(ecdsa(r %b)(s %b)))",
1222 (int)sizeof (sig->r), sig->r,
1223 (int)sizeof (sig->s), sig->s)))
1225 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
1226 return GNUNET_SYSERR;
1228 data = data_to_ecdsa_value (validate);
1229 if (0 != (rc = gcry_sexp_build (&pub_sexpr, NULL,
1230 "(public-key(ecc(curve " CURVE ")(q %b)))",
1231 (int)sizeof (pub->q_y), pub->q_y)))
1233 gcry_sexp_release (data);
1234 gcry_sexp_release (sig_sexpr);
1235 return GNUNET_SYSERR;
1237 rc = gcry_pk_verify (sig_sexpr, data, pub_sexpr);
1238 gcry_sexp_release (pub_sexpr);
1239 gcry_sexp_release (data);
1240 gcry_sexp_release (sig_sexpr);
1243 LOG (GNUNET_ERROR_TYPE_INFO,
1244 _("ECDSA signature verification failed at %s:%d: %s\n"), __FILE__,
1245 __LINE__, gcry_strerror (rc));
1246 return GNUNET_SYSERR;
1256 * @param purpose what is the purpose that the signature should have?
1257 * @param validate block to validate (size, purpose, data)
1258 * @param sig signature that is being validated
1259 * @param pub public key of the signer
1260 * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1263 GNUNET_CRYPTO_eddsa_verify (uint32_t purpose,
1264 const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1265 const struct GNUNET_CRYPTO_EddsaSignature *sig,
1266 const struct GNUNET_CRYPTO_EddsaPublicKey *pub)
1269 gcry_sexp_t sig_sexpr;
1270 gcry_sexp_t pub_sexpr;
1273 if (purpose != ntohl (validate->purpose))
1274 return GNUNET_SYSERR; /* purpose mismatch */
1276 /* build s-expression for signature */
1277 if (0 != (rc = gcry_sexp_build (&sig_sexpr, NULL,
1278 "(sig-val(eddsa(r %b)(s %b)))",
1279 (int)sizeof (sig->r), sig->r,
1280 (int)sizeof (sig->s), sig->s)))
1282 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
1283 return GNUNET_SYSERR;
1285 data = data_to_eddsa_value (validate);
1286 if (0 != (rc = gcry_sexp_build (&pub_sexpr, NULL,
1287 "(public-key(ecc(curve " CURVE ")(q %b)))",
1288 (int)sizeof (pub->q_y), pub->q_y)))
1290 gcry_sexp_release (data);
1291 gcry_sexp_release (sig_sexpr);
1292 return GNUNET_SYSERR;
1294 rc = gcry_pk_verify (sig_sexpr, data, pub_sexpr);
1295 gcry_sexp_release (pub_sexpr);
1296 gcry_sexp_release (data);
1297 gcry_sexp_release (sig_sexpr);
1300 LOG (GNUNET_ERROR_TYPE_INFO,
1301 _("EdDSA signature verification failed at %s:%d: %s\n"), __FILE__,
1302 __LINE__, gcry_strerror (rc));
1303 return GNUNET_SYSERR;
1310 * Derive key material from a public and a private ECDHE key.
1312 * @param priv private key to use for the ECDH (x)
1313 * @param pub public key to use for the ECDH (yG)
1314 * @param key_material where to write the key material (xyG)
1315 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1318 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1319 const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1320 struct GNUNET_HashCode *key_material)
1322 gcry_mpi_point_t result;
1326 gcry_sexp_t pub_sexpr;
1327 gcry_mpi_t result_x;
1328 unsigned char xbuf[256 / 8];
1331 /* first, extract the q = dP value from the public key */
1332 if (0 != gcry_sexp_build (&pub_sexpr, NULL,
1333 "(public-key(ecc(curve " CURVE ")(q %b)))",
1334 (int)sizeof (pub->q_y), pub->q_y))
1335 return GNUNET_SYSERR;
1336 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, pub_sexpr, NULL));
1337 gcry_sexp_release (pub_sexpr);
1338 q = gcry_mpi_ec_get_point ("q", ctx, 0);
1340 /* second, extract the d value from our private key */
1341 GNUNET_CRYPTO_mpi_scan_unsigned (&d, priv->d, sizeof (priv->d));
1343 /* then call the 'multiply' function, to compute the product */
1344 result = gcry_mpi_point_new (0);
1345 gcry_mpi_ec_mul (result, d, q, ctx);
1346 gcry_mpi_point_release (q);
1347 gcry_mpi_release (d);
1349 /* finally, convert point to string for hashing */
1350 result_x = gcry_mpi_new (256);
1351 if (gcry_mpi_ec_get_affine (result_x, NULL, result, ctx))
1353 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
1354 gcry_mpi_point_release (result);
1355 gcry_ctx_release (ctx);
1356 return GNUNET_SYSERR;
1358 gcry_mpi_point_release (result);
1359 gcry_ctx_release (ctx);
1361 rsize = sizeof (xbuf);
1362 GNUNET_assert (! gcry_mpi_get_flag (result_x, GCRYMPI_FLAG_OPAQUE));
1363 /* result_x can be negative here, so we do not use 'GNUNET_CRYPTO_mpi_print_unsigned'
1364 as that does not include the sign bit; x should be a 255-bit
1365 value, so with the sign it should fit snugly into the 256-bit
1368 gcry_mpi_print (GCRYMPI_FMT_STD, xbuf, rsize, &rsize,
1370 GNUNET_CRYPTO_hash (xbuf, rsize, key_material);
1371 gcry_mpi_release (result_x);
1377 * Derive the 'h' value for key derivation, where
1380 * @param pub public key for deriviation
1381 * @param label label for deriviation
1382 * @param context additional context to use for HKDF of 'h';
1383 * typically the name of the subsystem/application
1387 derive_h (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1389 const char *context)
1392 struct GNUNET_HashCode hc;
1394 GNUNET_CRYPTO_kdf (&hc, sizeof (hc),
1395 "key-derivation", strlen ("key-derivation"),
1397 label, strlen (label),
1398 context, strlen (context),
1400 GNUNET_CRYPTO_mpi_scan_unsigned (&h, (unsigned char *) &hc, sizeof (hc));
1406 * Derive a private key from a given private key and a label.
1407 * Essentially calculates a private key 'd = H(l,P) * x mod n'
1408 * where n is the size of the ECC group and P is the public
1409 * key associated with the private key 'd'.
1411 * @param priv original private key
1412 * @param label label to use for key deriviation
1413 * @param context additional context to use for HKDF of 'h';
1414 * typically the name of the subsystem/application
1415 * @return derived private key
1417 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1418 GNUNET_CRYPTO_ecdsa_private_key_derive (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1420 const char *context)
1422 struct GNUNET_CRYPTO_EcdsaPublicKey pub;
1423 struct GNUNET_CRYPTO_EcdsaPrivateKey *ret;
1430 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
1432 n = gcry_mpi_ec_get_mpi ("n", ctx, 1);
1433 GNUNET_CRYPTO_ecdsa_key_get_public (priv, &pub);
1435 h = derive_h (&pub, label, context);
1436 GNUNET_CRYPTO_mpi_scan_unsigned (&x, priv->d, sizeof (priv->d));
1437 d = gcry_mpi_new (256);
1438 gcry_mpi_mulm (d, h, x, n);
1439 gcry_mpi_release (h);
1440 gcry_mpi_release (x);
1441 gcry_mpi_release (n);
1442 gcry_ctx_release (ctx);
1443 ret = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPrivateKey);
1444 GNUNET_CRYPTO_mpi_print_unsigned (ret->d, sizeof (ret->d), d);
1445 gcry_mpi_release (d);
1451 * Derive a public key from a given public key and a label.
1452 * Essentially calculates a public key 'V = H(l,P) * P'.
1454 * @param pub original public key
1455 * @param label label to use for key derivation
1456 * @param context additional context to use for HKDF of 'h';
1457 * typically the name of the subsystem/application
1458 * @param result where to write the derived public key
1461 GNUNET_CRYPTO_ecdsa_public_key_derive (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1463 const char *context,
1464 struct GNUNET_CRYPTO_EcdsaPublicKey *result)
1474 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
1476 /* obtain point 'q' from original public key. The provided 'q' is
1477 compressed thus we first store it in the context and then get it
1478 back as a (decompresssed) point. */
1479 q_y = gcry_mpi_set_opaque_copy (NULL, pub->q_y, 8*sizeof (pub->q_y));
1480 GNUNET_assert (q_y);
1481 GNUNET_assert (0 == gcry_mpi_ec_set_mpi ("q", q_y, ctx));
1482 gcry_mpi_release (q_y);
1483 q = gcry_mpi_ec_get_point ("q", ctx, 0);
1486 /* calculate h_mod_n = h % n */
1487 h = derive_h (pub, label, context);
1488 n = gcry_mpi_ec_get_mpi ("n", ctx, 1);
1489 h_mod_n = gcry_mpi_new (256);
1490 gcry_mpi_mod (h_mod_n, h, n);
1491 /* calculate v = h_mod_n * q */
1492 v = gcry_mpi_point_new (0);
1493 gcry_mpi_ec_mul (v, h_mod_n, q, ctx);
1494 gcry_mpi_release (h_mod_n);
1495 gcry_mpi_release (h);
1496 gcry_mpi_release (n);
1497 gcry_mpi_point_release (q);
1499 /* convert point 'v' to public key that we return */
1500 GNUNET_assert (0 == gcry_mpi_ec_set_point ("q", v, ctx));
1501 gcry_mpi_point_release (v);
1502 q_y = gcry_mpi_ec_get_mpi ("q@eddsa", ctx, 0);
1503 GNUNET_assert (q_y);
1504 GNUNET_CRYPTO_mpi_print_unsigned (result->q_y, sizeof result->q_y, q_y);
1505 gcry_mpi_release (q_y);
1506 gcry_ctx_release (ctx);
1510 /* end of crypto_ecc.c */