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 ALLOW_EXTRA_CHECKS
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 * NOTE: this will change to Curve25519 before GNUnet 0.10.0.
40 #define CURVE "NIST P-256"
42 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
44 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
46 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
49 * Log an error message at log-level 'level' that indicates
50 * a failure of the command 'cmd' with the message given
51 * by gcry_strerror(rc).
53 #define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0)
57 * Extract values from an S-expression.
59 * @param array where to store the result(s)
60 * @param sexp S-expression to parse
61 * @param topname top-level name in the S-expression that is of interest
62 * @param elems names of the elements to extract
63 * @return 0 on success
66 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
75 list = gcry_sexp_find_token (sexp, topname, 0);
78 l2 = gcry_sexp_cadr (list);
79 gcry_sexp_release (list);
85 for (s = elems; *s; s++, idx++)
87 l2 = gcry_sexp_find_token (list, s, 1);
90 for (i = 0; i < idx; i++)
95 gcry_sexp_release (list);
96 return 3; /* required parameter not found */
98 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
99 gcry_sexp_release (l2);
102 for (i = 0; i < idx; i++)
104 gcry_free (array[i]);
107 gcry_sexp_release (list);
108 return 4; /* required parameter is invalid */
111 gcry_sexp_release (list);
117 * If target != size, move @a target bytes to the end of the size-sized
118 * buffer and zero out the first @a target - @a size bytes.
120 * @param buf original buffer
121 * @param size number of bytes in @a buf
122 * @param target target size of the buffer
125 adjust (unsigned char *buf,
131 memmove (&buf[target - size], buf, size);
132 memset (buf, 0, target - size);
138 * Output the given MPI value to the given buffer.
140 * @param buf where to output to
141 * @param size number of bytes in @a buf
142 * @param val value to write to @a buf
145 mpi_print (unsigned char *buf,
153 gcry_mpi_print (GCRYMPI_FMT_USG, buf, rsize, &rsize,
155 adjust (buf, rsize, size);
160 * Convert data buffer into MPI value.
162 * @param result where to store MPI value (allocated)
163 * @param data raw data (GCRYMPI_FMT_USG)
164 * @param size number of bytes in data
167 mpi_scan (gcry_mpi_t *result,
168 const unsigned char *data,
173 if (0 != (rc = gcry_mpi_scan (result,
177 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
184 * Convert the given private key from the network format to the
185 * S-expression that can be used by libgcrypt.
187 * @param priv private key to decode
188 * @return NULL on error
191 decode_private_key (const struct GNUNET_CRYPTO_EccPrivateKey *priv)
200 rc = gcry_sexp_build (&result, NULL,
201 "(private-key(ecdsa(curve \"" CURVE "\")(d %m)))",
203 gcry_mpi_release (d);
206 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
210 if (0 != (rc = gcry_pk_testkey (result)))
212 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
221 * Initialize public key struct from the respective point
224 * @param q point on curve
225 * @param pub public key struct to initialize
226 * @param ctx context to use for ECC operations
229 point_to_public_sign_key (gcry_mpi_point_t q,
231 struct GNUNET_CRYPTO_EccPublicSignKey *pub)
236 q_x = gcry_mpi_new (256);
237 q_y = gcry_mpi_new (256);
238 if (gcry_mpi_ec_get_affine (q_x, q_y, q, ctx))
240 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
244 mpi_print (pub->q_x, sizeof (pub->q_x), q_x);
245 mpi_print (pub->q_y, sizeof (pub->q_y), q_y);
246 gcry_mpi_release (q_x);
247 gcry_mpi_release (q_y);
252 * Initialize public key struct from the respective point
255 * @param q point on curve
256 * @param pub public key struct to initialize
257 * @param ctx context to use for ECC operations
260 point_to_public_encrypt_key (gcry_mpi_point_t q,
262 struct GNUNET_CRYPTO_EccPublicEncryptKey *pub)
267 q_x = gcry_mpi_new (256);
268 q_y = gcry_mpi_new (256);
269 if (gcry_mpi_ec_get_affine (q_x, q_y, q, ctx))
271 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
275 mpi_print (pub->q_x, sizeof (pub->q_x), q_x);
276 mpi_print (pub->q_y, sizeof (pub->q_y), q_y);
277 gcry_mpi_release (q_x);
278 gcry_mpi_release (q_y);
283 * Extract the public key for the given private key.
285 * @param priv the private key
286 * @param pub where to write the public key
289 GNUNET_CRYPTO_ecc_key_get_public_for_signature (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
290 struct GNUNET_CRYPTO_EccPublicSignKey *pub)
296 sexp = decode_private_key (priv);
297 GNUNET_assert (NULL != sexp);
298 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL));
299 gcry_sexp_release (sexp);
300 q = gcry_mpi_ec_get_point ("q", ctx, 0);
301 point_to_public_sign_key (q, ctx, pub);
302 gcry_ctx_release (ctx);
303 gcry_mpi_point_release (q);
308 * Extract the public key for the given private key.
310 * @param priv the private key
311 * @param pub where to write the public key
314 GNUNET_CRYPTO_ecc_key_get_public_for_encryption (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
315 struct GNUNET_CRYPTO_EccPublicEncryptKey *pub)
321 sexp = decode_private_key (priv);
322 GNUNET_assert (NULL != sexp);
323 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL));
324 gcry_sexp_release (sexp);
325 q = gcry_mpi_ec_get_point ("q", ctx, 0);
326 point_to_public_encrypt_key (q, ctx, pub);
327 gcry_ctx_release (ctx);
328 gcry_mpi_point_release (q);
333 * Convert a public key to a string.
335 * @param pub key to convert
336 * @return string representing @a pub
339 GNUNET_CRYPTO_ecc_public_sign_key_to_string (const struct GNUNET_CRYPTO_EccPublicSignKey *pub)
342 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicSignKey)) * 8;
346 keylen += 5 - keylen % 5;
348 pubkeybuf = GNUNET_malloc (keylen + 1);
349 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
350 sizeof (struct GNUNET_CRYPTO_EccPublicSignKey),
355 GNUNET_free (pubkeybuf);
364 * Convert a string representing a public key to a public key.
366 * @param enc encoded public key
367 * @param enclen number of bytes in @a enc (without 0-terminator)
368 * @param pub where to store the public key
369 * @return #GNUNET_OK on success
372 GNUNET_CRYPTO_ecc_public_sign_key_from_string (const char *enc,
374 struct GNUNET_CRYPTO_EccPublicSignKey *pub)
376 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicSignKey)) * 8;
379 keylen += 5 - keylen % 5;
381 if (enclen != keylen)
382 return GNUNET_SYSERR;
384 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
386 sizeof (struct GNUNET_CRYPTO_EccPublicSignKey)))
387 return GNUNET_SYSERR;
393 * Convert the given public key from the network format to the
394 * S-expression that can be used by libgcrypt.
396 * @param pub public key to decode
397 * @return NULL on error
400 decode_public_sign_key (const struct GNUNET_CRYPTO_EccPublicSignKey *pub)
402 gcry_sexp_t pub_sexp;
408 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
409 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
410 q = gcry_mpi_point_new (256);
411 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
412 gcry_mpi_release (q_x);
413 gcry_mpi_release (q_y);
415 /* initialize 'ctx' with 'q' */
416 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
417 gcry_mpi_ec_set_point ("q", q, ctx);
418 gcry_mpi_point_release (q);
420 /* convert 'ctx' to 'sexp' */
421 GNUNET_assert (0 == gcry_pubkey_get_sexp (&pub_sexp, GCRY_PK_GET_PUBKEY, ctx));
422 gcry_ctx_release (ctx);
429 * Clear memory that was used to store a private key.
431 * @param pk location of the key
434 GNUNET_CRYPTO_ecc_key_clear (struct GNUNET_CRYPTO_EccPrivateKey *pk)
436 memset (pk, 0, sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
441 * Create a new private key. Caller must free return value.
443 * @return fresh private key
445 struct GNUNET_CRYPTO_EccPrivateKey *
446 GNUNET_CRYPTO_ecc_key_create ()
448 struct GNUNET_CRYPTO_EccPrivateKey *priv;
449 gcry_sexp_t priv_sexp;
450 gcry_sexp_t s_keyparam;
454 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
455 "(genkey(ecdsa(curve \"" CURVE "\")))")))
457 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
460 if (0 != (rc = gcry_pk_genkey (&priv_sexp, s_keyparam)))
462 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
463 gcry_sexp_release (s_keyparam);
466 gcry_sexp_release (s_keyparam);
468 if (0 != (rc = gcry_pk_testkey (priv_sexp)))
470 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
471 gcry_sexp_release (priv_sexp);
475 if (0 != (rc = key_from_sexp (&d, priv_sexp, "private-key", "d")))
477 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
478 gcry_sexp_release (priv_sexp);
481 gcry_sexp_release (priv_sexp);
482 priv = GNUNET_new (struct GNUNET_CRYPTO_EccPrivateKey);
483 mpi_print (priv->d, sizeof (priv->d), d);
484 gcry_mpi_release (d);
490 * Get the shared private key we use for anonymous users.
492 * @return "anonymous" private key
494 const struct GNUNET_CRYPTO_EccPrivateKey *
495 GNUNET_CRYPTO_ecc_key_get_anonymous ()
498 * 'anonymous' pseudonym (global static, d=1, public key = G
501 static struct GNUNET_CRYPTO_EccPrivateKey anonymous;
506 mpi_print (anonymous.d,
507 sizeof (anonymous.d),
515 * Wait for a short time (we're trying to lock a file or want
516 * to give another process a shot at finishing a disk write, etc.).
517 * Sleeps for 100ms (as that should be long enough for virtually all
518 * modern systems to context switch and allow another process to do
524 struct GNUNET_TIME_Relative timeout;
526 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
527 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
532 * Create a new private key by reading it from a file. If the
533 * files does not exist, create a new key and write it to the
534 * file. Caller must free return value. Note that this function
535 * can not guarantee that another process might not be trying
536 * the same operation on the same file at the same time.
537 * If the contents of the file
538 * are invalid the old file is deleted and a fresh key is
541 * @param filename name of file to use to store the key
542 * @return new private key, NULL on error (for example,
545 struct GNUNET_CRYPTO_EccPrivateKey *
546 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
548 struct GNUNET_CRYPTO_EccPrivateKey *priv;
549 struct GNUNET_DISK_FileHandle *fd;
554 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
556 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
558 fd = GNUNET_DISK_file_open (filename,
559 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
560 | GNUNET_DISK_OPEN_FAILIFEXISTS,
561 GNUNET_DISK_PERM_USER_READ |
562 GNUNET_DISK_PERM_USER_WRITE);
567 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
569 /* must exist but not be accessible, fail for good! */
570 if (0 != ACCESS (filename, R_OK))
571 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
573 GNUNET_break (0); /* what is going on!? */
578 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
583 GNUNET_DISK_file_lock (fd, 0,
584 sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
591 LOG (GNUNET_ERROR_TYPE_ERROR,
592 _("Could not acquire lock on file `%s': %s...\n"), filename,
596 LOG (GNUNET_ERROR_TYPE_INFO,
597 _("Creating a new private key. This may take a while.\n"));
598 priv = GNUNET_CRYPTO_ecc_key_create ();
599 GNUNET_assert (NULL != priv);
600 GNUNET_assert (sizeof (*priv) ==
601 GNUNET_DISK_file_write (fd, priv, sizeof (*priv)));
602 GNUNET_DISK_file_sync (fd);
604 GNUNET_DISK_file_unlock (fd, 0,
605 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
606 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
607 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
610 /* key file exists already, read it! */
611 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
612 GNUNET_DISK_PERM_NONE);
615 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
622 GNUNET_DISK_file_lock (fd, 0,
623 sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
629 LOG (GNUNET_ERROR_TYPE_ERROR,
630 _("Could not acquire lock on file `%s': %s...\n"), filename,
632 LOG (GNUNET_ERROR_TYPE_ERROR,
634 ("This may be ok if someone is currently generating a private key.\n"));
639 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
641 /* eh, what!? File we opened is now gone!? */
642 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
644 GNUNET_DISK_file_unlock (fd, 0,
645 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
646 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
647 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
651 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
653 if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKey))
655 /* maybe we got the read lock before the key generating
656 * process had a chance to get the write lock; give it up! */
658 GNUNET_DISK_file_unlock (fd, 0,
659 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
660 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
663 LOG (GNUNET_ERROR_TYPE_ERROR,
665 ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
666 filename, (unsigned int) fs,
667 (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
668 LOG (GNUNET_ERROR_TYPE_ERROR,
670 ("This may be ok if someone is currently generating a key.\n"));
672 short_wait (); /* wait a bit longer! */
677 fs = sizeof (struct GNUNET_CRYPTO_EccPrivateKey);
678 priv = GNUNET_malloc (fs);
679 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, priv, fs));
681 GNUNET_DISK_file_unlock (fd, 0,
682 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
683 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
684 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
690 * Create a new private key by reading our peer's key from
691 * the file specified in the configuration.
693 * @param cfg the configuration to use
694 * @return new private key, NULL on error (for example,
697 struct GNUNET_CRYPTO_EccPrivateKey *
698 GNUNET_CRYPTO_ecc_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
700 struct GNUNET_CRYPTO_EccPrivateKey *priv;
704 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
706 priv = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
713 * Setup a key file for a peer given the name of the
714 * configuration file (!). This function is used so that
715 * at a later point code can be certain that reading a
716 * key is fast (for example in time-dependent testcases).
718 * @param cfg_name name of the configuration file to use
721 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
723 struct GNUNET_CONFIGURATION_Handle *cfg;
724 struct GNUNET_CRYPTO_EccPrivateKey *priv;
726 cfg = GNUNET_CONFIGURATION_create ();
727 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
728 priv = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg);
731 GNUNET_CONFIGURATION_destroy (cfg);
736 * Retrieve the identity of the host's peer.
738 * @param cfg configuration to use
739 * @param dst pointer to where to write the peer identity
740 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the identity
741 * could not be retrieved
744 GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
745 struct GNUNET_PeerIdentity *dst)
747 struct GNUNET_CRYPTO_EccPrivateKey *priv;
749 if (NULL == (priv = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg)))
751 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
752 _("Could not load peer's private key\n"));
753 return GNUNET_SYSERR;
755 GNUNET_CRYPTO_ecc_key_get_public_for_signature (priv, &dst->public_key);
762 * Convert the data specified in the given purpose argument to an
763 * S-expression suitable for signature operations.
765 * @param purpose data to convert
766 * @return converted s-expression
769 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
771 struct GNUNET_HashCode hc;
775 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
776 if (0 != (rc = gcry_sexp_build (&data, NULL,
777 "(data(flags rfc6979)(hash %s %b))",
782 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
790 * Sign a given block.
792 * @param priv private key to use for the signing
793 * @param purpose what to sign (size, purpose)
794 * @param sig where to write the signature
795 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
798 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
799 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
800 struct GNUNET_CRYPTO_EccSignature *sig)
802 gcry_sexp_t priv_sexp;
803 gcry_sexp_t sig_sexp;
808 priv_sexp = decode_private_key (priv);
809 data = data_to_pkcs1 (purpose);
810 if (0 != (rc = gcry_pk_sign (&sig_sexp, data, priv_sexp)))
812 LOG (GNUNET_ERROR_TYPE_WARNING,
813 _("ECC signing failed at %s:%d: %s\n"), __FILE__,
814 __LINE__, gcry_strerror (rc));
815 gcry_sexp_release (data);
816 gcry_sexp_release (priv_sexp);
817 return GNUNET_SYSERR;
819 gcry_sexp_release (priv_sexp);
820 gcry_sexp_release (data);
822 /* extract 'r' and 's' values from sexpression 'sig_sexp' and store in
824 if (0 != (rc = key_from_sexp (rs, sig_sexp, "sig-val", "rs")))
827 gcry_sexp_release (sig_sexp);
828 return GNUNET_SYSERR;
830 gcry_sexp_release (sig_sexp);
831 mpi_print (sig->r, sizeof (sig->r), rs[0]);
832 mpi_print (sig->s, sizeof (sig->s), rs[1]);
833 gcry_mpi_release (rs[0]);
834 gcry_mpi_release (rs[1]);
842 * @param purpose what is the purpose that the signature should have?
843 * @param validate block to validate (size, purpose, data)
844 * @param sig signature that is being validated
845 * @param pub public key of the signer
846 * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
849 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
850 const struct GNUNET_CRYPTO_EccSignaturePurpose
852 const struct GNUNET_CRYPTO_EccSignature *sig,
853 const struct GNUNET_CRYPTO_EccPublicSignKey *pub)
856 gcry_sexp_t sig_sexpr;
857 gcry_sexp_t pub_sexpr;
862 if (purpose != ntohl (validate->purpose))
863 return GNUNET_SYSERR; /* purpose mismatch */
865 /* build s-expression for signature */
866 mpi_scan (&r, sig->r, sizeof (sig->r));
867 mpi_scan (&s, sig->s, sizeof (sig->s));
868 if (0 != (rc = gcry_sexp_build (&sig_sexpr, NULL,
869 "(sig-val(ecdsa(r %m)(s %m)))",
872 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
873 gcry_mpi_release (r);
874 gcry_mpi_release (s);
875 return GNUNET_SYSERR;
877 gcry_mpi_release (r);
878 gcry_mpi_release (s);
879 data = data_to_pkcs1 (validate);
880 if (! (pub_sexpr = decode_public_sign_key (pub)))
882 gcry_sexp_release (data);
883 gcry_sexp_release (sig_sexpr);
884 return GNUNET_SYSERR;
886 rc = gcry_pk_verify (sig_sexpr, data, pub_sexpr);
887 gcry_sexp_release (pub_sexpr);
888 gcry_sexp_release (data);
889 gcry_sexp_release (sig_sexpr);
892 LOG (GNUNET_ERROR_TYPE_INFO,
893 _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
894 __LINE__, gcry_strerror (rc));
895 return GNUNET_SYSERR;
902 * Convert the given public key from the network format to the
903 * S-expression that can be used by libgcrypt.
905 * @param pub public key to decode
906 * @return NULL on error
909 decode_public_encrypt_key (const struct GNUNET_CRYPTO_EccPublicEncryptKey *pub)
911 gcry_sexp_t pub_sexp;
917 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
918 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
919 q = gcry_mpi_point_new (256);
920 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
921 gcry_mpi_release (q_x);
922 gcry_mpi_release (q_y);
924 /* initialize 'ctx' with 'q' */
925 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
926 gcry_mpi_ec_set_point ("q", q, ctx);
927 gcry_mpi_point_release (q);
929 /* convert 'ctx' to 'sexp' */
930 GNUNET_assert (0 == gcry_pubkey_get_sexp (&pub_sexp, GCRY_PK_GET_PUBKEY, ctx));
931 gcry_ctx_release (ctx);
937 * Derive key material from a public and a private ECC key.
939 * @param priv private key to use for the ECDH (x)
940 * @param pub public key to use for the ECDH (yG)
941 * @param key_material where to write the key material (xyG)
942 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
945 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
946 const struct GNUNET_CRYPTO_EccPublicEncryptKey *pub,
947 struct GNUNET_HashCode *key_material)
949 gcry_mpi_point_t result;
953 gcry_sexp_t pub_sexpr;
956 unsigned char xbuf[256 / 8];
958 /* first, extract the q = dP value from the public key */
959 if (! (pub_sexpr = decode_public_encrypt_key (pub)))
960 return GNUNET_SYSERR;
961 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, pub_sexpr, NULL));
962 gcry_sexp_release (pub_sexpr);
963 q = gcry_mpi_ec_get_point ("q", ctx, 0);
965 /* second, extract the d value from our private key */
966 mpi_scan (&d, priv->d, sizeof (priv->d));
968 /* then call the 'multiply' function, to compute the product */
969 result = gcry_mpi_point_new (0);
970 gcry_mpi_ec_mul (result, d, q, ctx);
971 gcry_mpi_point_release (q);
972 gcry_mpi_release (d);
974 /* finally, convert point to string for hashing */
975 result_x = gcry_mpi_new (256);
976 result_y = gcry_mpi_new (256);
977 if (gcry_mpi_ec_get_affine (result_x, result_y, result, ctx))
979 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
980 gcry_mpi_point_release (result);
981 gcry_ctx_release (ctx);
982 return GNUNET_SYSERR;
984 gcry_mpi_point_release (result);
985 gcry_ctx_release (ctx);
987 mpi_print (xbuf, sizeof (xbuf), result_x);
988 GNUNET_CRYPTO_hash (xbuf, sizeof (xbuf), key_material);
989 gcry_mpi_release (result_x);
990 gcry_mpi_release (result_y);
996 * Derive the 'h' value for key derivation, where
999 * @param pub public key for deriviation
1000 * @param label label for deriviation
1001 * @param context additional context to use for HKDF of 'h';
1002 * typically the name of the subsystem/application
1006 derive_h (const struct GNUNET_CRYPTO_EccPublicSignKey *pub,
1008 const char *context)
1011 struct GNUNET_HashCode hc;
1013 GNUNET_CRYPTO_kdf (&hc, sizeof (hc),
1014 "key-derivation", strlen ("key-derivation"),
1016 label, strlen (label),
1017 context, strlen (context),
1019 mpi_scan (&h, (unsigned char *) &hc, sizeof (hc));
1025 * Derive a private key from a given private key and a label.
1026 * Essentially calculates a private key 'd = H(l,P) * x mod n'
1027 * where n is the size of the ECC group and P is the public
1028 * key associated with the private key 'd'.
1030 * @param priv original private key
1031 * @param label label to use for key deriviation
1032 * @param context additional context to use for HKDF of 'h';
1033 * typically the name of the subsystem/application
1034 * @return derived private key
1036 struct GNUNET_CRYPTO_EccPrivateKey *
1037 GNUNET_CRYPTO_ecc_key_derive (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
1039 const char *context)
1041 struct GNUNET_CRYPTO_EccPublicSignKey pub;
1042 struct GNUNET_CRYPTO_EccPrivateKey *ret;
1049 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
1050 n = gcry_mpi_ec_get_mpi ("n", ctx, 1);
1051 GNUNET_CRYPTO_ecc_key_get_public_for_signature (priv, &pub);
1052 h = derive_h (&pub, label, context);
1053 mpi_scan (&x, priv->d, sizeof (priv->d));
1054 d = gcry_mpi_new (256);
1055 gcry_mpi_mulm (d, h, x, n);
1056 gcry_mpi_release (h);
1057 gcry_mpi_release (x);
1058 gcry_mpi_release (n);
1059 gcry_ctx_release (ctx);
1060 ret = GNUNET_new (struct GNUNET_CRYPTO_EccPrivateKey);
1061 mpi_print (ret->d, sizeof (ret->d), d);
1062 gcry_mpi_release (d);
1068 * Derive a public key from a given public key and a label.
1069 * Essentially calculates a public key 'V = H(l,P) * P'.
1071 * @param pub original public key
1072 * @param label label to use for key deriviation
1073 * @param context additional context to use for HKDF of 'h';
1074 * typically the name of the subsystem/application
1075 * @param result where to write the derived public key
1078 GNUNET_CRYPTO_ecc_public_key_derive (const struct GNUNET_CRYPTO_EccPublicSignKey *pub,
1080 const char *context,
1081 struct GNUNET_CRYPTO_EccPublicSignKey *result)
1092 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
1094 /* obtain point 'q' from original public key */
1095 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
1096 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
1098 q = gcry_mpi_point_new (0);
1099 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
1100 gcry_mpi_release (q_x);
1101 gcry_mpi_release (q_y);
1103 /* calulcate h_mod_n = h % n */
1104 h = derive_h (pub, label, context);
1105 n = gcry_mpi_ec_get_mpi ("n", ctx, 1);
1106 h_mod_n = gcry_mpi_new (256);
1107 gcry_mpi_mod (h_mod_n, h, n);
1108 /* calculate v = h_mod_n * q */
1109 v = gcry_mpi_point_new (0);
1110 gcry_mpi_ec_mul (v, h_mod_n, q, ctx);
1111 gcry_mpi_release (h_mod_n);
1112 gcry_mpi_release (h);
1113 gcry_mpi_release (n);
1114 gcry_mpi_point_release (q);
1115 /* convert point 'v' to public key that we return */
1116 point_to_public_sign_key (v, ctx, result);
1117 gcry_mpi_point_release (v);
1118 gcry_ctx_release (ctx);
1122 /* end of crypto_ecc.c */