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_common.h"
29 #include "gnunet_util_lib.h"
31 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
34 * Name of the curve we are using. Note that we have hard-coded
35 * structs that use 256 bits, so using a bigger curve will require
36 * changes that break stuff badly. The name of the curve given here
37 * must be agreed by all peers and be supported by libgcrypt.
39 #define CURVE "NIST P-256"
41 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
43 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
45 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
48 * Log an error message at log-level 'level' that indicates
49 * a failure of the command 'cmd' with the message given
50 * by gcry_strerror(rc).
52 #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);
56 * Free memory occupied by ECC key
58 * @param priv pointer to the memory to free
61 GNUNET_CRYPTO_ecc_key_free (struct GNUNET_CRYPTO_EccPrivateKey *priv)
68 * Extract values from an S-expression.
70 * @param array where to store the result(s)
71 * @param sexp S-expression to parse
72 * @param topname top-level name in the S-expression that is of interest
73 * @param elems names of the elements to extract
74 * @return 0 on success
77 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
86 list = gcry_sexp_find_token (sexp, topname, 0);
89 l2 = gcry_sexp_cadr (list);
90 gcry_sexp_release (list);
96 for (s = elems; *s; s++, idx++)
98 l2 = gcry_sexp_find_token (list, s, 1);
101 for (i = 0; i < idx; i++)
103 gcry_free (array[i]);
106 gcry_sexp_release (list);
107 return 3; /* required parameter not found */
109 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
110 gcry_sexp_release (l2);
113 for (i = 0; i < idx; i++)
115 gcry_free (array[i]);
118 gcry_sexp_release (list);
119 return 4; /* required parameter is invalid */
122 gcry_sexp_release (list);
128 * If target != size, move target bytes to the end of the size-sized
129 * buffer and zero out the first target-size bytes.
131 * @param buf original buffer
132 * @param size number of bytes in the buffer
133 * @param target target size of the buffer
136 adjust (unsigned char *buf,
142 memmove (&buf[target - size], buf, size);
143 memset (buf, 0, target - size);
149 * Output the given MPI value to the given buffer.
151 * @param buf where to output to
152 * @param size number of bytes in buf
153 * @param val value to write to buf
156 mpi_print (unsigned char *buf,
164 gcry_mpi_print (GCRYMPI_FMT_USG, buf, rsize, &rsize,
166 adjust (buf, rsize, size);
171 * Convert data buffer into MPI value.
173 * @param result where to store MPI value (allocated)
174 * @param data raw data (GCRYMPI_FMT_USG)
175 * @param size number of bytes in data
178 mpi_scan (gcry_mpi_t *result,
179 const unsigned char *data,
184 if (0 != (rc = gcry_mpi_scan (result,
188 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
195 * Convert the given private key from the network format to the
196 * S-expression that can be used by libgcrypt.
198 * @param priv private key to decode
199 * @return NULL on error
202 decode_private_key (const struct GNUNET_CRYPTO_EccPrivateKey *priv)
212 rc = gcry_sexp_build (&result, &erroff,
213 "(private-key(ecdsa(curve \"" CURVE "\")(d %m)))",
215 gcry_mpi_release (d);
218 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
222 if (0 != (rc = gcry_pk_testkey (result)))
224 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
233 * Initialize public key struct from the respective point
236 * @param q point on curve
237 * @param pub public key struct to initialize
238 * @param ctx context to use for ECC operations
241 point_to_public_key (gcry_mpi_point_t q,
243 struct GNUNET_CRYPTO_EccPublicKey *pub)
248 q_x = gcry_mpi_new (256);
249 q_y = gcry_mpi_new (256);
250 if (gcry_mpi_ec_get_affine (q_x, q_y, q, ctx))
252 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
255 mpi_print (pub->q_x, sizeof (pub->q_x), q_x);
256 mpi_print (pub->q_y, sizeof (pub->q_y), q_y);
257 gcry_mpi_release (q_x);
258 gcry_mpi_release (q_y);
263 * Extract the public key for the given private key.
265 * @param priv the private key
266 * @param pub where to write the public key
269 GNUNET_CRYPTO_ecc_key_get_public (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
270 struct GNUNET_CRYPTO_EccPublicKey *pub)
277 sexp = decode_private_key (priv);
278 GNUNET_assert (NULL != sexp);
279 if (0 != (rc = gcry_mpi_ec_new (&ctx, sexp, NULL)))
281 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc); /* erroff gives more info */
284 gcry_sexp_release (sexp);
285 q = gcry_mpi_ec_get_point ("q", ctx, 0);
286 point_to_public_key (q, ctx, pub);
287 gcry_ctx_release (ctx);
288 gcry_mpi_point_release (q);
293 * Convert a public key to a string.
295 * @param pub key to convert
296 * @return string representing 'pub'
299 GNUNET_CRYPTO_ecc_public_key_to_string (const struct GNUNET_CRYPTO_EccPublicKey *pub)
302 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKey)) * 8;
306 keylen += 5 - keylen % 5;
308 pubkeybuf = GNUNET_malloc (keylen + 1);
309 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
310 sizeof (struct GNUNET_CRYPTO_EccPublicKey),
315 GNUNET_free (pubkeybuf);
324 * Convert a string representing a public key to a public key.
326 * @param enc encoded public key
327 * @param enclen number of bytes in enc (without 0-terminator)
328 * @param pub where to store the public key
329 * @return GNUNET_OK on success
332 GNUNET_CRYPTO_ecc_public_key_from_string (const char *enc,
334 struct GNUNET_CRYPTO_EccPublicKey *pub)
336 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKey)) * 8;
339 keylen += 5 - keylen % 5;
341 if (enclen != keylen)
342 return GNUNET_SYSERR;
344 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
346 sizeof (struct GNUNET_CRYPTO_EccPublicKey)))
347 return GNUNET_SYSERR;
353 * Convert the given public key from the network format to the
354 * S-expression that can be used by libgcrypt.
356 * @param pub public key to decode
357 * @return NULL on error
360 decode_public_key (const struct GNUNET_CRYPTO_EccPublicKey *pub)
362 gcry_sexp_t pub_sexp;
369 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
370 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
371 q = gcry_mpi_point_new (256);
372 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
373 gcry_mpi_release (q_x);
374 gcry_mpi_release (q_y);
376 /* create basic ECC context */
377 if (0 != (rc = gcry_mpi_ec_new (&ctx, NULL, CURVE)))
379 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc); /* erroff gives more info */
380 gcry_mpi_point_release (q);
383 /* initialize 'ctx' with 'q' */
384 gcry_mpi_ec_set_point ("q", q, ctx);
385 gcry_mpi_point_release (q);
387 /* convert 'ctx' to 'sexp' */
388 if (0 != (rc = gcry_pubkey_get_sexp (&pub_sexp, GCRY_PK_GET_PUBKEY, ctx)))
390 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_from_context", rc);
391 gcry_ctx_release (ctx);
394 gcry_ctx_release (ctx);
400 * Create a new private key. Caller must free return value.
402 * @return fresh private key
404 struct GNUNET_CRYPTO_EccPrivateKey *
405 GNUNET_CRYPTO_ecc_key_create ()
407 struct GNUNET_CRYPTO_EccPrivateKey *priv;
408 gcry_sexp_t priv_sexp;
409 gcry_sexp_t s_keyparam;
413 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
414 "(genkey(ecdsa(curve \"" CURVE "\")))")))
416 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
419 if (0 != (rc = gcry_pk_genkey (&priv_sexp, s_keyparam)))
421 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
422 gcry_sexp_release (s_keyparam);
425 gcry_sexp_release (s_keyparam);
427 if (0 != (rc = gcry_pk_testkey (priv_sexp)))
429 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
430 gcry_sexp_release (priv_sexp);
434 if (0 != (rc = key_from_sexp (&d, priv_sexp, "private-key", "d")))
436 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
437 gcry_sexp_release (priv_sexp);
440 gcry_sexp_release (priv_sexp);
441 priv = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
442 mpi_print (priv->d, sizeof (priv->d), d);
443 gcry_mpi_release (d);
449 * Wait for a short time (we're trying to lock a file or want
450 * to give another process a shot at finishing a disk write, etc.).
451 * Sleeps for 100ms (as that should be long enough for virtually all
452 * modern systems to context switch and allow another process to do
458 struct GNUNET_TIME_Relative timeout;
460 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
461 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
466 * Create a new private key by reading it from a file. If the
467 * files does not exist, create a new key and write it to the
468 * file. Caller must free return value. Note that this function
469 * can not guarantee that another process might not be trying
470 * the same operation on the same file at the same time.
471 * If the contents of the file
472 * are invalid the old file is deleted and a fresh key is
475 * @param filename name of file to use to store the key
476 * @return new private key, NULL on error (for example,
479 struct GNUNET_CRYPTO_EccPrivateKey *
480 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
482 struct GNUNET_CRYPTO_EccPrivateKey *priv;
483 struct GNUNET_DISK_FileHandle *fd;
488 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
490 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
492 fd = GNUNET_DISK_file_open (filename,
493 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
494 | GNUNET_DISK_OPEN_FAILIFEXISTS,
495 GNUNET_DISK_PERM_USER_READ |
496 GNUNET_DISK_PERM_USER_WRITE);
501 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
503 /* must exist but not be accessible, fail for good! */
504 if (0 != ACCESS (filename, R_OK))
505 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
507 GNUNET_break (0); /* what is going on!? */
512 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
518 GNUNET_DISK_file_lock (fd, 0,
519 sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
526 LOG (GNUNET_ERROR_TYPE_ERROR,
527 _("Could not acquire lock on file `%s': %s...\n"), filename,
531 LOG (GNUNET_ERROR_TYPE_INFO,
532 _("Creating a new private key. This may take a while.\n"));
533 priv = GNUNET_CRYPTO_ecc_key_create ();
534 GNUNET_assert (NULL != priv);
535 GNUNET_assert (sizeof (*priv) ==
536 GNUNET_DISK_file_write (fd, priv, sizeof (*priv)));
537 GNUNET_DISK_file_sync (fd);
539 GNUNET_DISK_file_unlock (fd, 0,
540 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
541 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
542 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
545 /* key file exists already, read it! */
546 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
547 GNUNET_DISK_PERM_NONE);
550 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
557 GNUNET_DISK_file_lock (fd, 0,
558 sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
564 LOG (GNUNET_ERROR_TYPE_ERROR,
565 _("Could not acquire lock on file `%s': %s...\n"), filename,
567 LOG (GNUNET_ERROR_TYPE_ERROR,
569 ("This may be ok if someone is currently generating a private key.\n"));
574 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
576 /* eh, what!? File we opened is now gone!? */
577 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
579 GNUNET_DISK_file_unlock (fd, 0,
580 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
581 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
582 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
586 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
588 if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKey))
590 /* maybe we got the read lock before the key generating
591 * process had a chance to get the write lock; give it up! */
593 GNUNET_DISK_file_unlock (fd, 0,
594 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
595 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
598 LOG (GNUNET_ERROR_TYPE_ERROR,
600 ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
601 filename, (unsigned int) fs,
602 (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
603 LOG (GNUNET_ERROR_TYPE_ERROR,
605 ("This may be ok if someone is currently generating a key.\n"));
607 short_wait (); /* wait a bit longer! */
612 fs = sizeof (struct GNUNET_CRYPTO_EccPrivateKey);
613 priv = GNUNET_malloc (fs);
614 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, priv, fs));
616 GNUNET_DISK_file_unlock (fd, 0,
617 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
618 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
619 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
625 * Create a new private key by reading our peer's key from
626 * the file specified in the configuration.
628 * @return new private key, NULL on error (for example,
631 struct GNUNET_CRYPTO_EccPrivateKey *
632 GNUNET_CRYPTO_ecc_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
634 struct GNUNET_CRYPTO_EccPrivateKey *priv;
638 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
640 priv = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
647 * Setup a key file for a peer given the name of the
648 * configuration file (!). This function is used so that
649 * at a later point code can be certain that reading a
650 * key is fast (for example in time-dependent testcases).
652 * @param cfg_name name of the configuration file to use
655 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
657 struct GNUNET_CONFIGURATION_Handle *cfg;
658 struct GNUNET_CRYPTO_EccPrivateKey *priv;
660 cfg = GNUNET_CONFIGURATION_create ();
661 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
662 priv = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg);
664 GNUNET_CRYPTO_ecc_key_free (priv);
665 GNUNET_CONFIGURATION_destroy (cfg);
670 * Retrieve the identity of the host's peer.
672 * @param cfg configuration to use
673 * @param dst pointer to where to write the peer identity
674 * @return GNUNET_OK on success, GNUNET_SYSERR if the identity
675 * could not be retrieved
678 GNUNET_CRYPTO_get_host_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
679 struct GNUNET_PeerIdentity *dst)
681 struct GNUNET_CRYPTO_EccPrivateKey *priv;
682 struct GNUNET_CRYPTO_EccPublicKey pub;
684 if (NULL == (priv = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg)))
686 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
687 _("Could not load peer's private key\n"));
688 return GNUNET_SYSERR;
690 GNUNET_CRYPTO_ecc_key_get_public (priv, &pub);
691 GNUNET_CRYPTO_ecc_key_free (priv);
692 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &dst->hashPubKey);
698 * Convert the data specified in the given purpose argument to an
699 * S-expression suitable for signature operations.
701 * @param purpose data to convert
702 * @return converted s-expression
705 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
707 struct GNUNET_CRYPTO_ShortHashCode hc;
711 GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
712 if (0 != (rc = gcry_sexp_build (&data, NULL,
713 "(data(flags rfc6979)(hash %s %b))",
718 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
726 * Sign a given block.
728 * @param priv private key to use for the signing
729 * @param purpose what to sign (size, purpose)
730 * @param sig where to write the signature
731 * @return GNUNET_SYSERR on error, GNUNET_OK on success
734 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
735 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
736 struct GNUNET_CRYPTO_EccSignature *sig)
738 gcry_sexp_t priv_sexp;
739 gcry_sexp_t sig_sexp;
744 priv_sexp = decode_private_key (priv);
745 data = data_to_pkcs1 (purpose);
746 if (0 != (rc = gcry_pk_sign (&sig_sexp, data, priv_sexp)))
748 LOG (GNUNET_ERROR_TYPE_WARNING,
749 _("ECC signing failed at %s:%d: %s\n"), __FILE__,
750 __LINE__, gcry_strerror (rc));
751 gcry_sexp_release (data);
752 gcry_sexp_release (priv_sexp);
753 return GNUNET_SYSERR;
755 gcry_sexp_release (priv_sexp);
756 gcry_sexp_release (data);
758 /* extract 'r' and 's' values from sexpression 'sig_sexp' and store in
760 if (0 != (rc = key_from_sexp (rs, sig_sexp, "sig-val", "rs")))
763 gcry_sexp_release (sig_sexp);
764 return GNUNET_SYSERR;
766 gcry_sexp_release (sig_sexp);
767 mpi_print (sig->r, sizeof (sig->r), rs[0]);
768 mpi_print (sig->s, sizeof (sig->s), rs[1]);
769 gcry_mpi_release (rs[0]);
770 gcry_mpi_release (rs[1]);
778 * @param purpose what is the purpose that the signature should have?
779 * @param validate block to validate (size, purpose, data)
780 * @param sig signature that is being validated
781 * @param pub public key of the signer
782 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
785 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
786 const struct GNUNET_CRYPTO_EccSignaturePurpose
788 const struct GNUNET_CRYPTO_EccSignature *sig,
789 const struct GNUNET_CRYPTO_EccPublicKey *pub)
792 gcry_sexp_t sig_sexpr;
793 gcry_sexp_t pub_sexpr;
799 if (purpose != ntohl (validate->purpose))
800 return GNUNET_SYSERR; /* purpose mismatch */
802 /* build s-expression for signature */
803 mpi_scan (&r, sig->r, sizeof (sig->r));
804 mpi_scan (&s, sig->s, sizeof (sig->s));
805 if (0 != (rc = gcry_sexp_build (&sig_sexpr, &erroff, "(sig-val(ecdsa(r %m)(s %m)))",
808 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
809 gcry_mpi_release (r);
810 gcry_mpi_release (s);
811 return GNUNET_SYSERR;
813 gcry_mpi_release (r);
814 gcry_mpi_release (s);
815 data = data_to_pkcs1 (validate);
816 if (! (pub_sexpr = decode_public_key (pub)))
818 gcry_sexp_release (data);
819 gcry_sexp_release (sig_sexpr);
820 return GNUNET_SYSERR;
822 rc = gcry_pk_verify (sig_sexpr, data, pub_sexpr);
823 gcry_sexp_release (pub_sexpr);
824 gcry_sexp_release (data);
825 gcry_sexp_release (sig_sexpr);
828 LOG (GNUNET_ERROR_TYPE_WARNING,
829 _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
830 __LINE__, gcry_strerror (rc));
831 return GNUNET_SYSERR;
838 * Derive key material from a public and a private ECC key.
840 * @param priv private key to use for the ECDH (x)
841 * @param pub public key to use for the ECDH (yG)
842 * @param key_material where to write the key material (xyG)
843 * @return GNUNET_SYSERR on error, GNUNET_OK on success
846 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
847 const struct GNUNET_CRYPTO_EccPublicKey *pub,
848 struct GNUNET_HashCode *key_material)
853 unsigned char sdata_buf[2048]; /* big enough to print dh-shared-secret as S-expression */
854 gcry_mpi_point_t result;
858 gcry_sexp_t pub_sexpr;
859 gcry_sexp_t ecdh_sexp;
863 /* first, extract the q = dP value from the public key */
864 if (! (pub_sexpr = decode_public_key (pub)))
865 return GNUNET_SYSERR;
866 if (0 != (rc = gcry_mpi_ec_new (&ctx, pub_sexpr, NULL)))
868 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc); /* erroff gives more info */
869 return GNUNET_SYSERR;
871 gcry_sexp_release (pub_sexpr);
872 q = gcry_mpi_ec_get_point ("q", ctx, 0);
873 gcry_ctx_release (ctx);
875 /* second, extract the d value from our private key */
876 mpi_scan (&d, priv->d, sizeof (priv->d));
878 /* create a new context for definitively the correct curve;
879 theoretically the 'public_key' might not use the right curve */
880 if (0 != (rc = gcry_mpi_ec_new (&ctx, NULL, CURVE)))
882 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc); /* erroff gives more info */
883 gcry_mpi_release (d);
884 gcry_mpi_point_release (q);
885 return GNUNET_SYSERR;
888 /* then call the 'multiply' function, to compute the product */
889 GNUNET_assert (NULL != ctx);
890 result = gcry_mpi_point_new (0);
891 gcry_mpi_ec_mul (result, d, q, ctx);
892 gcry_mpi_point_release (q);
893 gcry_mpi_release (d);
895 /* finally, convert point to string for hashing */
896 result_x = gcry_mpi_new (256);
897 result_y = gcry_mpi_new (256);
898 if (gcry_mpi_ec_get_affine (result_x, result_y, result, ctx))
900 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
901 gcry_mpi_point_release (result);
902 gcry_ctx_release (ctx);
903 return GNUNET_SYSERR;
905 gcry_mpi_point_release (result);
906 gcry_ctx_release (ctx);
907 if (0 != (rc = gcry_sexp_build (&ecdh_sexp, &erroff,
908 "(dh-shared-secret (x %m)(y %m))",
912 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
913 gcry_mpi_release (result_x);
914 gcry_mpi_release (result_y);
915 return GNUNET_SYSERR;
917 gcry_mpi_release (result_x);
918 gcry_mpi_release (result_y);
919 slen = gcry_sexp_sprint (ecdh_sexp,
920 GCRYSEXP_FMT_DEFAULT,
921 sdata_buf, sizeof (sdata_buf));
922 GNUNET_assert (0 != slen);
923 gcry_sexp_release (ecdh_sexp);
924 /* finally, get a string of the resulting S-expression and hash it
925 to generate the key material */
926 GNUNET_CRYPTO_hash (sdata_buf, slen, key_material);
932 * Derive the 'h' value for key derivation, where
935 * @param pub public key for deriviation
936 * @param label label for deriviation
940 derive_h (const struct GNUNET_CRYPTO_EccPublicKey *pub,
944 struct GNUNET_HashCode hc;
946 GNUNET_CRYPTO_kdf (&hc, sizeof (hc),
947 "key-derivation", strlen ("key-derivation"),
949 label, sizeof (label),
951 mpi_scan (&h, (unsigned char *) &hc, sizeof (hc));
957 * Derive a private key from a given private key and a label.
958 * Essentially calculates a private key 'd = H(l,P) * x mod n'
959 * where n is the size of the ECC group and P is the public
960 * key associated with the private key 'd'.
962 * @param priv original private key
963 * @param label label to use for key deriviation
964 * @return derived private key
966 struct GNUNET_CRYPTO_EccPrivateKey *
967 GNUNET_CRYPTO_ecc_key_derive (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
970 struct GNUNET_CRYPTO_EccPublicKey pub;
971 struct GNUNET_CRYPTO_EccPrivateKey *ret;
978 GNUNET_CRYPTO_ecc_key_get_public (priv, &pub);
979 h = derive_h (&pub, label);
980 mpi_scan (&x, priv->d, sizeof (priv->d));
981 /* initialize 'n' from P-256; hex copied from libgcrypt code */
982 if (0 != (rc = gcry_mpi_scan (&n, GCRYMPI_FMT_HEX,
983 "0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", 0, NULL)))
985 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
986 gcry_mpi_release (h);
989 d = gcry_mpi_new (256);
990 gcry_mpi_mulm (d, h, x, n);
991 gcry_mpi_release (h);
992 gcry_mpi_release (x);
993 gcry_mpi_release (n);
994 ret = GNUNET_new (struct GNUNET_CRYPTO_EccPrivateKey);
995 mpi_print (ret->d, sizeof (ret->d), d);
996 gcry_mpi_release (d);
1002 * Derive a public key from a given public key and a label.
1003 * Essentially calculates a public key 'V = H(l,P) * P'.
1005 * @param pub original public key
1006 * @param label label to use for key deriviation
1007 * @param result where to write the derived public key
1010 GNUNET_CRYPTO_ecc_public_key_derive (const struct GNUNET_CRYPTO_EccPublicKey *pub,
1012 struct GNUNET_CRYPTO_EccPublicKey *result)
1022 h = derive_h (pub, label);
1023 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
1024 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
1025 q = gcry_mpi_point_new (256);
1026 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
1027 gcry_mpi_release (q_x);
1028 gcry_mpi_release (q_y);
1030 /* create basic ECC context */
1031 if (0 != (rc = gcry_mpi_ec_new (&ctx, NULL, CURVE)))
1033 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc);
1034 gcry_mpi_point_release (q);
1035 gcry_mpi_release (h);
1038 v = gcry_mpi_point_new (256);
1039 /* we could calculate 'h mod n' here first, but hopefully
1040 libgcrypt is smart enough to do that for us... */
1041 gcry_mpi_ec_mul (v, h, q, ctx);
1042 gcry_mpi_release (h);
1043 gcry_mpi_point_release (q);
1044 point_to_public_key (v, ctx, result);
1045 gcry_mpi_point_release (v);
1046 gcry_ctx_release (ctx);
1050 /* end of crypto_ecc.c */