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 * NOTE: this will change to Curve25519 before GNUnet 0.10.0.
41 #define CURVE "NIST P-256"
43 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
45 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
47 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
50 * Log an error message at log-level 'level' that indicates
51 * a failure of the command 'cmd' with the message given
52 * by gcry_strerror(rc).
54 #define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0)
58 * Extract values from an S-expression.
60 * @param array where to store the result(s)
61 * @param sexp S-expression to parse
62 * @param topname top-level name in the S-expression that is of interest
63 * @param elems names of the elements to extract
64 * @return 0 on success
67 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
76 list = gcry_sexp_find_token (sexp, topname, 0);
79 l2 = gcry_sexp_cadr (list);
80 gcry_sexp_release (list);
86 for (s = elems; *s; s++, idx++)
88 l2 = gcry_sexp_find_token (list, s, 1);
91 for (i = 0; i < idx; i++)
96 gcry_sexp_release (list);
97 return 3; /* required parameter not found */
99 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
100 gcry_sexp_release (l2);
103 for (i = 0; i < idx; i++)
105 gcry_free (array[i]);
108 gcry_sexp_release (list);
109 return 4; /* required parameter is invalid */
112 gcry_sexp_release (list);
118 * If target != size, move @a target bytes to the end of the size-sized
119 * buffer and zero out the first @a target - @a size bytes.
121 * @param buf original buffer
122 * @param size number of bytes in @a buf
123 * @param target target size of the buffer
126 adjust (unsigned char *buf,
132 memmove (&buf[target - size], buf, size);
133 memset (buf, 0, target - size);
139 * Output the given MPI value to the given buffer.
141 * @param buf where to output to
142 * @param size number of bytes in @a buf
143 * @param val value to write to @a buf
146 mpi_print (unsigned char *buf,
154 gcry_mpi_print (GCRYMPI_FMT_USG, buf, rsize, &rsize,
156 adjust (buf, rsize, size);
161 * Convert data buffer into MPI value.
163 * @param result where to store MPI value (allocated)
164 * @param data raw data (GCRYMPI_FMT_USG)
165 * @param size number of bytes in data
168 mpi_scan (gcry_mpi_t *result,
169 const unsigned char *data,
174 if (0 != (rc = gcry_mpi_scan (result,
178 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
185 * Convert the given private key from the network format to the
186 * S-expression that can be used by libgcrypt.
188 * @param priv private key to decode
189 * @return NULL on error
192 decode_private_key (const struct GNUNET_CRYPTO_EccPrivateKey *priv)
201 rc = gcry_sexp_build (&result, NULL,
202 "(private-key(ecdsa(curve \"" CURVE "\")(d %m)))",
204 gcry_mpi_release (d);
207 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
211 if (0 != (rc = gcry_pk_testkey (result)))
213 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
222 * Initialize public key struct from the respective point
225 * @param q point on curve
226 * @param pub public key struct to initialize
227 * @param ctx context to use for ECC operations
230 point_to_public_key (gcry_mpi_point_t q,
232 struct GNUNET_CRYPTO_EccPublicSignKey *pub)
237 q_x = gcry_mpi_new (256);
238 q_y = gcry_mpi_new (256);
239 if (gcry_mpi_ec_get_affine (q_x, q_y, q, ctx))
241 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
245 mpi_print (pub->q_x, sizeof (pub->q_x), q_x);
246 mpi_print (pub->q_y, sizeof (pub->q_y), q_y);
247 gcry_mpi_release (q_x);
248 gcry_mpi_release (q_y);
253 * Extract the public key for the given private key.
255 * @param priv the private key
256 * @param pub where to write the public key
259 GNUNET_CRYPTO_ecc_key_get_public_for_signature (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
260 struct GNUNET_CRYPTO_EccPublicSignKey *pub)
266 sexp = decode_private_key (priv);
267 GNUNET_assert (NULL != sexp);
268 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL));
269 gcry_sexp_release (sexp);
270 q = gcry_mpi_ec_get_point ("q", ctx, 0);
271 point_to_public_key (q, ctx, pub);
272 gcry_ctx_release (ctx);
273 gcry_mpi_point_release (q);
278 * Convert a public key to a string.
280 * @param pub key to convert
281 * @return string representing @a pub
284 GNUNET_CRYPTO_ecc_public_sign_key_to_string (const struct GNUNET_CRYPTO_EccPublicSignKey *pub)
287 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicSignKey)) * 8;
291 keylen += 5 - keylen % 5;
293 pubkeybuf = GNUNET_malloc (keylen + 1);
294 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
295 sizeof (struct GNUNET_CRYPTO_EccPublicSignKey),
300 GNUNET_free (pubkeybuf);
309 * Convert a string representing a public key to a public key.
311 * @param enc encoded public key
312 * @param enclen number of bytes in @a enc (without 0-terminator)
313 * @param pub where to store the public key
314 * @return #GNUNET_OK on success
317 GNUNET_CRYPTO_ecc_public_sign_key_from_string (const char *enc,
319 struct GNUNET_CRYPTO_EccPublicSignKey *pub)
321 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicSignKey)) * 8;
324 keylen += 5 - keylen % 5;
326 if (enclen != keylen)
327 return GNUNET_SYSERR;
329 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
331 sizeof (struct GNUNET_CRYPTO_EccPublicSignKey)))
332 return GNUNET_SYSERR;
338 * Convert the given public key from the network format to the
339 * S-expression that can be used by libgcrypt.
341 * @param pub public key to decode
342 * @return NULL on error
345 decode_public_sign_key (const struct GNUNET_CRYPTO_EccPublicSignKey *pub)
347 gcry_sexp_t pub_sexp;
353 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
354 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
355 q = gcry_mpi_point_new (256);
356 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
357 gcry_mpi_release (q_x);
358 gcry_mpi_release (q_y);
360 /* initialize 'ctx' with 'q' */
361 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
362 gcry_mpi_ec_set_point ("q", q, ctx);
363 gcry_mpi_point_release (q);
365 /* convert 'ctx' to 'sexp' */
366 GNUNET_assert (0 == gcry_pubkey_get_sexp (&pub_sexp, GCRY_PK_GET_PUBKEY, ctx));
367 gcry_ctx_release (ctx);
373 * Create a new private key. Caller must free return value.
375 * @return fresh private key
377 struct GNUNET_CRYPTO_EccPrivateKey *
378 GNUNET_CRYPTO_ecc_key_create ()
380 struct GNUNET_CRYPTO_EccPrivateKey *priv;
381 gcry_sexp_t priv_sexp;
382 gcry_sexp_t s_keyparam;
386 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
387 "(genkey(ecdsa(curve \"" CURVE "\")))")))
389 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
392 if (0 != (rc = gcry_pk_genkey (&priv_sexp, s_keyparam)))
394 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
395 gcry_sexp_release (s_keyparam);
398 gcry_sexp_release (s_keyparam);
400 if (0 != (rc = gcry_pk_testkey (priv_sexp)))
402 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
403 gcry_sexp_release (priv_sexp);
407 if (0 != (rc = key_from_sexp (&d, priv_sexp, "private-key", "d")))
409 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
410 gcry_sexp_release (priv_sexp);
413 gcry_sexp_release (priv_sexp);
414 priv = GNUNET_new (struct GNUNET_CRYPTO_EccPrivateKey);
415 mpi_print (priv->d, sizeof (priv->d), d);
416 gcry_mpi_release (d);
422 * Get the shared private key we use for anonymous users.
424 * @return "anonymous" private key
426 const struct GNUNET_CRYPTO_EccPrivateKey *
427 GNUNET_CRYPTO_ecc_key_get_anonymous ()
430 * 'anonymous' pseudonym (global static, d=1, public key = G
433 static struct GNUNET_CRYPTO_EccPrivateKey anonymous;
438 mpi_print (anonymous.d,
439 sizeof (anonymous.d),
447 * Wait for a short time (we're trying to lock a file or want
448 * to give another process a shot at finishing a disk write, etc.).
449 * Sleeps for 100ms (as that should be long enough for virtually all
450 * modern systems to context switch and allow another process to do
456 struct GNUNET_TIME_Relative timeout;
458 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
459 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
464 * Create a new private key by reading it from a file. If the
465 * files does not exist, create a new key and write it to the
466 * file. Caller must free return value. Note that this function
467 * can not guarantee that another process might not be trying
468 * the same operation on the same file at the same time.
469 * If the contents of the file
470 * are invalid the old file is deleted and a fresh key is
473 * @param filename name of file to use to store the key
474 * @return new private key, NULL on error (for example,
477 struct GNUNET_CRYPTO_EccPrivateKey *
478 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
480 struct GNUNET_CRYPTO_EccPrivateKey *priv;
481 struct GNUNET_DISK_FileHandle *fd;
486 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
488 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
490 fd = GNUNET_DISK_file_open (filename,
491 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
492 | GNUNET_DISK_OPEN_FAILIFEXISTS,
493 GNUNET_DISK_PERM_USER_READ |
494 GNUNET_DISK_PERM_USER_WRITE);
499 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
501 /* must exist but not be accessible, fail for good! */
502 if (0 != ACCESS (filename, R_OK))
503 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
505 GNUNET_break (0); /* what is going on!? */
510 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
515 GNUNET_DISK_file_lock (fd, 0,
516 sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
523 LOG (GNUNET_ERROR_TYPE_ERROR,
524 _("Could not acquire lock on file `%s': %s...\n"), filename,
528 LOG (GNUNET_ERROR_TYPE_INFO,
529 _("Creating a new private key. This may take a while.\n"));
530 priv = GNUNET_CRYPTO_ecc_key_create ();
531 GNUNET_assert (NULL != priv);
532 GNUNET_assert (sizeof (*priv) ==
533 GNUNET_DISK_file_write (fd, priv, sizeof (*priv)));
534 GNUNET_DISK_file_sync (fd);
536 GNUNET_DISK_file_unlock (fd, 0,
537 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
538 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
539 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
542 /* key file exists already, read it! */
543 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
544 GNUNET_DISK_PERM_NONE);
547 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
554 GNUNET_DISK_file_lock (fd, 0,
555 sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
561 LOG (GNUNET_ERROR_TYPE_ERROR,
562 _("Could not acquire lock on file `%s': %s...\n"), filename,
564 LOG (GNUNET_ERROR_TYPE_ERROR,
566 ("This may be ok if someone is currently generating a private key.\n"));
571 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
573 /* eh, what!? File we opened is now gone!? */
574 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
576 GNUNET_DISK_file_unlock (fd, 0,
577 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
578 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
579 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
583 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
585 if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKey))
587 /* maybe we got the read lock before the key generating
588 * process had a chance to get the write lock; give it up! */
590 GNUNET_DISK_file_unlock (fd, 0,
591 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
592 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
595 LOG (GNUNET_ERROR_TYPE_ERROR,
597 ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
598 filename, (unsigned int) fs,
599 (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
600 LOG (GNUNET_ERROR_TYPE_ERROR,
602 ("This may be ok if someone is currently generating a key.\n"));
604 short_wait (); /* wait a bit longer! */
609 fs = sizeof (struct GNUNET_CRYPTO_EccPrivateKey);
610 priv = GNUNET_malloc (fs);
611 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, priv, fs));
613 GNUNET_DISK_file_unlock (fd, 0,
614 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
615 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
616 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
622 * Create a new private key by reading our peer's key from
623 * the file specified in the configuration.
625 * @param cfg the configuration to use
626 * @return new private key, NULL on error (for example,
629 struct GNUNET_CRYPTO_EccPrivateKey *
630 GNUNET_CRYPTO_ecc_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
632 struct GNUNET_CRYPTO_EccPrivateKey *priv;
636 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
638 priv = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
645 * Setup a key file for a peer given the name of the
646 * configuration file (!). This function is used so that
647 * at a later point code can be certain that reading a
648 * key is fast (for example in time-dependent testcases).
650 * @param cfg_name name of the configuration file to use
653 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
655 struct GNUNET_CONFIGURATION_Handle *cfg;
656 struct GNUNET_CRYPTO_EccPrivateKey *priv;
658 cfg = GNUNET_CONFIGURATION_create ();
659 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
660 priv = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg);
663 GNUNET_CONFIGURATION_destroy (cfg);
668 * Retrieve the identity of the host's peer.
670 * @param cfg configuration to use
671 * @param dst pointer to where to write the peer identity
672 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the identity
673 * could not be retrieved
676 GNUNET_CRYPTO_get_host_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
677 struct GNUNET_PeerIdentity *dst)
679 struct GNUNET_CRYPTO_EccPrivateKey *priv;
680 struct GNUNET_CRYPTO_EccPublicSignKey pub;
682 if (NULL == (priv = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg)))
684 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
685 _("Could not load peer's private key\n"));
686 return GNUNET_SYSERR;
688 GNUNET_CRYPTO_ecc_key_get_public_for_signature (priv, &pub);
690 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &dst->hashPubKey);
696 * Convert the data specified in the given purpose argument to an
697 * S-expression suitable for signature operations.
699 * @param purpose data to convert
700 * @return converted s-expression
703 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
705 struct GNUNET_HashCode hc;
709 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
710 if (0 != (rc = gcry_sexp_build (&data, NULL,
711 "(data(flags rfc6979)(hash %s %b))",
716 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
724 * Sign a given block.
726 * @param priv private key to use for the signing
727 * @param purpose what to sign (size, purpose)
728 * @param sig where to write the signature
729 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
732 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
733 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
734 struct GNUNET_CRYPTO_EccSignature *sig)
736 gcry_sexp_t priv_sexp;
737 gcry_sexp_t sig_sexp;
742 priv_sexp = decode_private_key (priv);
743 data = data_to_pkcs1 (purpose);
744 if (0 != (rc = gcry_pk_sign (&sig_sexp, data, priv_sexp)))
746 LOG (GNUNET_ERROR_TYPE_WARNING,
747 _("ECC signing failed at %s:%d: %s\n"), __FILE__,
748 __LINE__, gcry_strerror (rc));
749 gcry_sexp_release (data);
750 gcry_sexp_release (priv_sexp);
751 return GNUNET_SYSERR;
753 gcry_sexp_release (priv_sexp);
754 gcry_sexp_release (data);
756 /* extract 'r' and 's' values from sexpression 'sig_sexp' and store in
758 if (0 != (rc = key_from_sexp (rs, sig_sexp, "sig-val", "rs")))
761 gcry_sexp_release (sig_sexp);
762 return GNUNET_SYSERR;
764 gcry_sexp_release (sig_sexp);
765 mpi_print (sig->r, sizeof (sig->r), rs[0]);
766 mpi_print (sig->s, sizeof (sig->s), rs[1]);
767 gcry_mpi_release (rs[0]);
768 gcry_mpi_release (rs[1]);
776 * @param purpose what is the purpose that the signature should have?
777 * @param validate block to validate (size, purpose, data)
778 * @param sig signature that is being validated
779 * @param pub public key of the signer
780 * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
783 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
784 const struct GNUNET_CRYPTO_EccSignaturePurpose
786 const struct GNUNET_CRYPTO_EccSignature *sig,
787 const struct GNUNET_CRYPTO_EccPublicSignKey *pub)
790 gcry_sexp_t sig_sexpr;
791 gcry_sexp_t pub_sexpr;
796 if (purpose != ntohl (validate->purpose))
797 return GNUNET_SYSERR; /* purpose mismatch */
799 /* build s-expression for signature */
800 mpi_scan (&r, sig->r, sizeof (sig->r));
801 mpi_scan (&s, sig->s, sizeof (sig->s));
802 if (0 != (rc = gcry_sexp_build (&sig_sexpr, NULL,
803 "(sig-val(ecdsa(r %m)(s %m)))",
806 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
807 gcry_mpi_release (r);
808 gcry_mpi_release (s);
809 return GNUNET_SYSERR;
811 gcry_mpi_release (r);
812 gcry_mpi_release (s);
813 data = data_to_pkcs1 (validate);
814 if (! (pub_sexpr = decode_public_sign_key (pub)))
816 gcry_sexp_release (data);
817 gcry_sexp_release (sig_sexpr);
818 return GNUNET_SYSERR;
820 rc = gcry_pk_verify (sig_sexpr, data, pub_sexpr);
821 gcry_sexp_release (pub_sexpr);
822 gcry_sexp_release (data);
823 gcry_sexp_release (sig_sexpr);
826 LOG (GNUNET_ERROR_TYPE_INFO,
827 _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
828 __LINE__, gcry_strerror (rc));
829 return GNUNET_SYSERR;
836 * Convert the given public key from the network format to the
837 * S-expression that can be used by libgcrypt.
839 * @param pub public key to decode
840 * @return NULL on error
843 decode_public_encrypt_key (const struct GNUNET_CRYPTO_EccPublicEncryptKey *pub)
845 gcry_sexp_t pub_sexp;
851 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
852 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
853 q = gcry_mpi_point_new (256);
854 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
855 gcry_mpi_release (q_x);
856 gcry_mpi_release (q_y);
858 /* initialize 'ctx' with 'q' */
859 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
860 gcry_mpi_ec_set_point ("q", q, ctx);
861 gcry_mpi_point_release (q);
863 /* convert 'ctx' to 'sexp' */
864 GNUNET_assert (0 == gcry_pubkey_get_sexp (&pub_sexp, GCRY_PK_GET_PUBKEY, ctx));
865 gcry_ctx_release (ctx);
871 * Derive key material from a public and a private ECC key.
873 * @param priv private key to use for the ECDH (x)
874 * @param pub public key to use for the ECDH (yG)
875 * @param key_material where to write the key material (xyG)
876 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
879 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
880 const struct GNUNET_CRYPTO_EccPublicEncryptKey *pub,
881 struct GNUNET_HashCode *key_material)
883 gcry_mpi_point_t result;
887 gcry_sexp_t pub_sexpr;
890 unsigned char xbuf[256 / 8];
892 /* first, extract the q = dP value from the public key */
893 if (! (pub_sexpr = decode_public_encrypt_key (pub)))
894 return GNUNET_SYSERR;
895 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, pub_sexpr, NULL));
896 gcry_sexp_release (pub_sexpr);
897 q = gcry_mpi_ec_get_point ("q", ctx, 0);
899 /* second, extract the d value from our private key */
900 mpi_scan (&d, priv->d, sizeof (priv->d));
902 /* then call the 'multiply' function, to compute the product */
903 result = gcry_mpi_point_new (0);
904 gcry_mpi_ec_mul (result, d, q, ctx);
905 gcry_mpi_point_release (q);
906 gcry_mpi_release (d);
908 /* finally, convert point to string for hashing */
909 result_x = gcry_mpi_new (256);
910 result_y = gcry_mpi_new (256);
911 if (gcry_mpi_ec_get_affine (result_x, result_y, result, ctx))
913 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
914 gcry_mpi_point_release (result);
915 gcry_ctx_release (ctx);
916 return GNUNET_SYSERR;
918 gcry_mpi_point_release (result);
919 gcry_ctx_release (ctx);
921 mpi_print (xbuf, sizeof (xbuf), result_x);
922 GNUNET_CRYPTO_hash (xbuf, sizeof (xbuf), key_material);
923 gcry_mpi_release (result_x);
924 gcry_mpi_release (result_y);
930 * Derive the 'h' value for key derivation, where
933 * @param pub public key for deriviation
934 * @param label label for deriviation
935 * @param context additional context to use for HKDF of 'h';
936 * typically the name of the subsystem/application
940 derive_h (const struct GNUNET_CRYPTO_EccPublicSignKey *pub,
945 struct GNUNET_HashCode hc;
947 GNUNET_CRYPTO_kdf (&hc, sizeof (hc),
948 "key-derivation", strlen ("key-derivation"),
950 label, strlen (label),
951 context, strlen (context),
953 mpi_scan (&h, (unsigned char *) &hc, sizeof (hc));
959 * Derive a private key from a given private key and a label.
960 * Essentially calculates a private key 'd = H(l,P) * x mod n'
961 * where n is the size of the ECC group and P is the public
962 * key associated with the private key 'd'.
964 * @param priv original private key
965 * @param label label to use for key deriviation
966 * @param context additional context to use for HKDF of 'h';
967 * typically the name of the subsystem/application
968 * @return derived private key
970 struct GNUNET_CRYPTO_EccPrivateKey *
971 GNUNET_CRYPTO_ecc_key_derive (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
975 struct GNUNET_CRYPTO_EccPublicSignKey pub;
976 struct GNUNET_CRYPTO_EccPrivateKey *ret;
983 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
984 n = gcry_mpi_ec_get_mpi ("n", ctx, 1);
985 GNUNET_CRYPTO_ecc_key_get_public_for_signature (priv, &pub);
986 h = derive_h (&pub, label, context);
987 mpi_scan (&x, priv->d, sizeof (priv->d));
988 d = gcry_mpi_new (256);
989 gcry_mpi_mulm (d, h, x, n);
990 gcry_mpi_release (h);
991 gcry_mpi_release (x);
992 gcry_mpi_release (n);
993 gcry_ctx_release (ctx);
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 context additional context to use for HKDF of 'h';
1008 * typically the name of the subsystem/application
1009 * @param result where to write the derived public key
1012 GNUNET_CRYPTO_ecc_public_key_derive (const struct GNUNET_CRYPTO_EccPublicSignKey *pub,
1014 const char *context,
1015 struct GNUNET_CRYPTO_EccPublicSignKey *result)
1026 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
1028 /* obtain point 'q' from original public key */
1029 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
1030 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
1032 q = gcry_mpi_point_new (0);
1033 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
1034 gcry_mpi_release (q_x);
1035 gcry_mpi_release (q_y);
1037 /* calulcate h_mod_n = h % n */
1038 h = derive_h (pub, label, context);
1039 n = gcry_mpi_ec_get_mpi ("n", ctx, 1);
1040 h_mod_n = gcry_mpi_new (256);
1041 gcry_mpi_mod (h_mod_n, h, n);
1042 /* calculate v = h_mod_n * q */
1043 v = gcry_mpi_point_new (0);
1044 gcry_mpi_ec_mul (v, h_mod_n, q, ctx);
1045 gcry_mpi_release (h_mod_n);
1046 gcry_mpi_release (h);
1047 gcry_mpi_release (n);
1048 gcry_mpi_point_release (q);
1049 /* convert point 'v' to public key that we return */
1050 point_to_public_key (v, ctx, result);
1051 gcry_mpi_point_release (v);
1052 gcry_ctx_release (ctx);
1056 /* end of crypto_ecc.c */