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_sign_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 * Initialize public key struct from the respective point
256 * @param q point on curve
257 * @param pub public key struct to initialize
258 * @param ctx context to use for ECC operations
261 point_to_public_encrypt_key (gcry_mpi_point_t q,
263 struct GNUNET_CRYPTO_EccPublicEncryptKey *pub)
268 q_x = gcry_mpi_new (256);
269 q_y = gcry_mpi_new (256);
270 if (gcry_mpi_ec_get_affine (q_x, q_y, q, ctx))
272 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
276 mpi_print (pub->q_x, sizeof (pub->q_x), q_x);
277 mpi_print (pub->q_y, sizeof (pub->q_y), q_y);
278 gcry_mpi_release (q_x);
279 gcry_mpi_release (q_y);
284 * Extract the public key for the given private key.
286 * @param priv the private key
287 * @param pub where to write the public key
290 GNUNET_CRYPTO_ecc_key_get_public_for_signature (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
291 struct GNUNET_CRYPTO_EccPublicSignKey *pub)
297 sexp = decode_private_key (priv);
298 GNUNET_assert (NULL != sexp);
299 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL));
300 gcry_sexp_release (sexp);
301 q = gcry_mpi_ec_get_point ("q", ctx, 0);
302 point_to_public_sign_key (q, ctx, pub);
303 gcry_ctx_release (ctx);
304 gcry_mpi_point_release (q);
309 * Extract the public key for the given private key.
311 * @param priv the private key
312 * @param pub where to write the public key
315 GNUNET_CRYPTO_ecc_key_get_public_for_encryption (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
316 struct GNUNET_CRYPTO_EccPublicEncryptKey *pub)
322 sexp = decode_private_key (priv);
323 GNUNET_assert (NULL != sexp);
324 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL));
325 gcry_sexp_release (sexp);
326 q = gcry_mpi_ec_get_point ("q", ctx, 0);
327 point_to_public_encrypt_key (q, ctx, pub);
328 gcry_ctx_release (ctx);
329 gcry_mpi_point_release (q);
334 * Convert a public key to a string.
336 * @param pub key to convert
337 * @return string representing @a pub
340 GNUNET_CRYPTO_ecc_public_sign_key_to_string (const struct GNUNET_CRYPTO_EccPublicSignKey *pub)
343 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicSignKey)) * 8;
347 keylen += 5 - keylen % 5;
349 pubkeybuf = GNUNET_malloc (keylen + 1);
350 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
351 sizeof (struct GNUNET_CRYPTO_EccPublicSignKey),
356 GNUNET_free (pubkeybuf);
365 * Convert a string representing a public key to a public key.
367 * @param enc encoded public key
368 * @param enclen number of bytes in @a enc (without 0-terminator)
369 * @param pub where to store the public key
370 * @return #GNUNET_OK on success
373 GNUNET_CRYPTO_ecc_public_sign_key_from_string (const char *enc,
375 struct GNUNET_CRYPTO_EccPublicSignKey *pub)
377 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicSignKey)) * 8;
380 keylen += 5 - keylen % 5;
382 if (enclen != keylen)
383 return GNUNET_SYSERR;
385 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
387 sizeof (struct GNUNET_CRYPTO_EccPublicSignKey)))
388 return GNUNET_SYSERR;
394 * Convert the given public key from the network format to the
395 * S-expression that can be used by libgcrypt.
397 * @param pub public key to decode
398 * @return NULL on error
401 decode_public_sign_key (const struct GNUNET_CRYPTO_EccPublicSignKey *pub)
403 gcry_sexp_t pub_sexp;
409 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
410 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
411 q = gcry_mpi_point_new (256);
412 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
413 gcry_mpi_release (q_x);
414 gcry_mpi_release (q_y);
416 /* initialize 'ctx' with 'q' */
417 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
418 gcry_mpi_ec_set_point ("q", q, ctx);
419 gcry_mpi_point_release (q);
421 /* convert 'ctx' to 'sexp' */
422 GNUNET_assert (0 == gcry_pubkey_get_sexp (&pub_sexp, GCRY_PK_GET_PUBKEY, ctx));
423 gcry_ctx_release (ctx);
429 * Create a new private key. Caller must free return value.
431 * @return fresh private key
433 struct GNUNET_CRYPTO_EccPrivateKey *
434 GNUNET_CRYPTO_ecc_key_create ()
436 struct GNUNET_CRYPTO_EccPrivateKey *priv;
437 gcry_sexp_t priv_sexp;
438 gcry_sexp_t s_keyparam;
442 if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
443 "(genkey(ecdsa(curve \"" CURVE "\")))")))
445 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
448 if (0 != (rc = gcry_pk_genkey (&priv_sexp, s_keyparam)))
450 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
451 gcry_sexp_release (s_keyparam);
454 gcry_sexp_release (s_keyparam);
456 if (0 != (rc = gcry_pk_testkey (priv_sexp)))
458 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
459 gcry_sexp_release (priv_sexp);
463 if (0 != (rc = key_from_sexp (&d, priv_sexp, "private-key", "d")))
465 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
466 gcry_sexp_release (priv_sexp);
469 gcry_sexp_release (priv_sexp);
470 priv = GNUNET_new (struct GNUNET_CRYPTO_EccPrivateKey);
471 mpi_print (priv->d, sizeof (priv->d), d);
472 gcry_mpi_release (d);
478 * Get the shared private key we use for anonymous users.
480 * @return "anonymous" private key
482 const struct GNUNET_CRYPTO_EccPrivateKey *
483 GNUNET_CRYPTO_ecc_key_get_anonymous ()
486 * 'anonymous' pseudonym (global static, d=1, public key = G
489 static struct GNUNET_CRYPTO_EccPrivateKey anonymous;
494 mpi_print (anonymous.d,
495 sizeof (anonymous.d),
503 * Wait for a short time (we're trying to lock a file or want
504 * to give another process a shot at finishing a disk write, etc.).
505 * Sleeps for 100ms (as that should be long enough for virtually all
506 * modern systems to context switch and allow another process to do
512 struct GNUNET_TIME_Relative timeout;
514 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
515 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
520 * Create a new private key by reading it from a file. If the
521 * files does not exist, create a new key and write it to the
522 * file. Caller must free return value. Note that this function
523 * can not guarantee that another process might not be trying
524 * the same operation on the same file at the same time.
525 * If the contents of the file
526 * are invalid the old file is deleted and a fresh key is
529 * @param filename name of file to use to store the key
530 * @return new private key, NULL on error (for example,
533 struct GNUNET_CRYPTO_EccPrivateKey *
534 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
536 struct GNUNET_CRYPTO_EccPrivateKey *priv;
537 struct GNUNET_DISK_FileHandle *fd;
542 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
544 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
546 fd = GNUNET_DISK_file_open (filename,
547 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
548 | GNUNET_DISK_OPEN_FAILIFEXISTS,
549 GNUNET_DISK_PERM_USER_READ |
550 GNUNET_DISK_PERM_USER_WRITE);
555 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
557 /* must exist but not be accessible, fail for good! */
558 if (0 != ACCESS (filename, R_OK))
559 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
561 GNUNET_break (0); /* what is going on!? */
566 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
571 GNUNET_DISK_file_lock (fd, 0,
572 sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
579 LOG (GNUNET_ERROR_TYPE_ERROR,
580 _("Could not acquire lock on file `%s': %s...\n"), filename,
584 LOG (GNUNET_ERROR_TYPE_INFO,
585 _("Creating a new private key. This may take a while.\n"));
586 priv = GNUNET_CRYPTO_ecc_key_create ();
587 GNUNET_assert (NULL != priv);
588 GNUNET_assert (sizeof (*priv) ==
589 GNUNET_DISK_file_write (fd, priv, sizeof (*priv)));
590 GNUNET_DISK_file_sync (fd);
592 GNUNET_DISK_file_unlock (fd, 0,
593 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
594 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
595 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
598 /* key file exists already, read it! */
599 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
600 GNUNET_DISK_PERM_NONE);
603 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
610 GNUNET_DISK_file_lock (fd, 0,
611 sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
617 LOG (GNUNET_ERROR_TYPE_ERROR,
618 _("Could not acquire lock on file `%s': %s...\n"), filename,
620 LOG (GNUNET_ERROR_TYPE_ERROR,
622 ("This may be ok if someone is currently generating a private key.\n"));
627 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
629 /* eh, what!? File we opened is now gone!? */
630 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
632 GNUNET_DISK_file_unlock (fd, 0,
633 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
634 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
635 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
639 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
641 if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKey))
643 /* maybe we got the read lock before the key generating
644 * process had a chance to get the write lock; give it up! */
646 GNUNET_DISK_file_unlock (fd, 0,
647 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
648 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
651 LOG (GNUNET_ERROR_TYPE_ERROR,
653 ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
654 filename, (unsigned int) fs,
655 (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
656 LOG (GNUNET_ERROR_TYPE_ERROR,
658 ("This may be ok if someone is currently generating a key.\n"));
660 short_wait (); /* wait a bit longer! */
665 fs = sizeof (struct GNUNET_CRYPTO_EccPrivateKey);
666 priv = GNUNET_malloc (fs);
667 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, priv, fs));
669 GNUNET_DISK_file_unlock (fd, 0,
670 sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
671 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
672 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
678 * Create a new private key by reading our peer's key from
679 * the file specified in the configuration.
681 * @param cfg the configuration to use
682 * @return new private key, NULL on error (for example,
685 struct GNUNET_CRYPTO_EccPrivateKey *
686 GNUNET_CRYPTO_ecc_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
688 struct GNUNET_CRYPTO_EccPrivateKey *priv;
692 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
694 priv = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
701 * Setup a key file for a peer given the name of the
702 * configuration file (!). This function is used so that
703 * at a later point code can be certain that reading a
704 * key is fast (for example in time-dependent testcases).
706 * @param cfg_name name of the configuration file to use
709 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
711 struct GNUNET_CONFIGURATION_Handle *cfg;
712 struct GNUNET_CRYPTO_EccPrivateKey *priv;
714 cfg = GNUNET_CONFIGURATION_create ();
715 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
716 priv = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg);
719 GNUNET_CONFIGURATION_destroy (cfg);
724 * Retrieve the identity of the host's peer.
726 * @param cfg configuration to use
727 * @param dst pointer to where to write the peer identity
728 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the identity
729 * could not be retrieved
732 GNUNET_CRYPTO_get_host_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
733 struct GNUNET_PeerIdentity *dst)
735 struct GNUNET_CRYPTO_EccPrivateKey *priv;
736 struct GNUNET_CRYPTO_EccPublicSignKey pub;
738 if (NULL == (priv = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg)))
740 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
741 _("Could not load peer's private key\n"));
742 return GNUNET_SYSERR;
744 GNUNET_CRYPTO_ecc_key_get_public_for_signature (priv, &pub);
746 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &dst->hashPubKey);
752 * Convert the data specified in the given purpose argument to an
753 * S-expression suitable for signature operations.
755 * @param purpose data to convert
756 * @return converted s-expression
759 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
761 struct GNUNET_HashCode hc;
765 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
766 if (0 != (rc = gcry_sexp_build (&data, NULL,
767 "(data(flags rfc6979)(hash %s %b))",
772 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
780 * Sign a given block.
782 * @param priv private key to use for the signing
783 * @param purpose what to sign (size, purpose)
784 * @param sig where to write the signature
785 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
788 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
789 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
790 struct GNUNET_CRYPTO_EccSignature *sig)
792 gcry_sexp_t priv_sexp;
793 gcry_sexp_t sig_sexp;
798 priv_sexp = decode_private_key (priv);
799 data = data_to_pkcs1 (purpose);
800 if (0 != (rc = gcry_pk_sign (&sig_sexp, data, priv_sexp)))
802 LOG (GNUNET_ERROR_TYPE_WARNING,
803 _("ECC signing failed at %s:%d: %s\n"), __FILE__,
804 __LINE__, gcry_strerror (rc));
805 gcry_sexp_release (data);
806 gcry_sexp_release (priv_sexp);
807 return GNUNET_SYSERR;
809 gcry_sexp_release (priv_sexp);
810 gcry_sexp_release (data);
812 /* extract 'r' and 's' values from sexpression 'sig_sexp' and store in
814 if (0 != (rc = key_from_sexp (rs, sig_sexp, "sig-val", "rs")))
817 gcry_sexp_release (sig_sexp);
818 return GNUNET_SYSERR;
820 gcry_sexp_release (sig_sexp);
821 mpi_print (sig->r, sizeof (sig->r), rs[0]);
822 mpi_print (sig->s, sizeof (sig->s), rs[1]);
823 gcry_mpi_release (rs[0]);
824 gcry_mpi_release (rs[1]);
832 * @param purpose what is the purpose that the signature should have?
833 * @param validate block to validate (size, purpose, data)
834 * @param sig signature that is being validated
835 * @param pub public key of the signer
836 * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
839 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
840 const struct GNUNET_CRYPTO_EccSignaturePurpose
842 const struct GNUNET_CRYPTO_EccSignature *sig,
843 const struct GNUNET_CRYPTO_EccPublicSignKey *pub)
846 gcry_sexp_t sig_sexpr;
847 gcry_sexp_t pub_sexpr;
852 if (purpose != ntohl (validate->purpose))
853 return GNUNET_SYSERR; /* purpose mismatch */
855 /* build s-expression for signature */
856 mpi_scan (&r, sig->r, sizeof (sig->r));
857 mpi_scan (&s, sig->s, sizeof (sig->s));
858 if (0 != (rc = gcry_sexp_build (&sig_sexpr, NULL,
859 "(sig-val(ecdsa(r %m)(s %m)))",
862 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
863 gcry_mpi_release (r);
864 gcry_mpi_release (s);
865 return GNUNET_SYSERR;
867 gcry_mpi_release (r);
868 gcry_mpi_release (s);
869 data = data_to_pkcs1 (validate);
870 if (! (pub_sexpr = decode_public_sign_key (pub)))
872 gcry_sexp_release (data);
873 gcry_sexp_release (sig_sexpr);
874 return GNUNET_SYSERR;
876 rc = gcry_pk_verify (sig_sexpr, data, pub_sexpr);
877 gcry_sexp_release (pub_sexpr);
878 gcry_sexp_release (data);
879 gcry_sexp_release (sig_sexpr);
882 LOG (GNUNET_ERROR_TYPE_INFO,
883 _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
884 __LINE__, gcry_strerror (rc));
885 return GNUNET_SYSERR;
892 * Convert the given public key from the network format to the
893 * S-expression that can be used by libgcrypt.
895 * @param pub public key to decode
896 * @return NULL on error
899 decode_public_encrypt_key (const struct GNUNET_CRYPTO_EccPublicEncryptKey *pub)
901 gcry_sexp_t pub_sexp;
907 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
908 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
909 q = gcry_mpi_point_new (256);
910 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
911 gcry_mpi_release (q_x);
912 gcry_mpi_release (q_y);
914 /* initialize 'ctx' with 'q' */
915 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
916 gcry_mpi_ec_set_point ("q", q, ctx);
917 gcry_mpi_point_release (q);
919 /* convert 'ctx' to 'sexp' */
920 GNUNET_assert (0 == gcry_pubkey_get_sexp (&pub_sexp, GCRY_PK_GET_PUBKEY, ctx));
921 gcry_ctx_release (ctx);
927 * Derive key material from a public and a private ECC key.
929 * @param priv private key to use for the ECDH (x)
930 * @param pub public key to use for the ECDH (yG)
931 * @param key_material where to write the key material (xyG)
932 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
935 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
936 const struct GNUNET_CRYPTO_EccPublicEncryptKey *pub,
937 struct GNUNET_HashCode *key_material)
939 gcry_mpi_point_t result;
943 gcry_sexp_t pub_sexpr;
946 unsigned char xbuf[256 / 8];
948 /* first, extract the q = dP value from the public key */
949 if (! (pub_sexpr = decode_public_encrypt_key (pub)))
950 return GNUNET_SYSERR;
951 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, pub_sexpr, NULL));
952 gcry_sexp_release (pub_sexpr);
953 q = gcry_mpi_ec_get_point ("q", ctx, 0);
955 /* second, extract the d value from our private key */
956 mpi_scan (&d, priv->d, sizeof (priv->d));
958 /* then call the 'multiply' function, to compute the product */
959 result = gcry_mpi_point_new (0);
960 gcry_mpi_ec_mul (result, d, q, ctx);
961 gcry_mpi_point_release (q);
962 gcry_mpi_release (d);
964 /* finally, convert point to string for hashing */
965 result_x = gcry_mpi_new (256);
966 result_y = gcry_mpi_new (256);
967 if (gcry_mpi_ec_get_affine (result_x, result_y, result, ctx))
969 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
970 gcry_mpi_point_release (result);
971 gcry_ctx_release (ctx);
972 return GNUNET_SYSERR;
974 gcry_mpi_point_release (result);
975 gcry_ctx_release (ctx);
977 mpi_print (xbuf, sizeof (xbuf), result_x);
978 GNUNET_CRYPTO_hash (xbuf, sizeof (xbuf), key_material);
979 gcry_mpi_release (result_x);
980 gcry_mpi_release (result_y);
986 * Derive the 'h' value for key derivation, where
989 * @param pub public key for deriviation
990 * @param label label for deriviation
991 * @param context additional context to use for HKDF of 'h';
992 * typically the name of the subsystem/application
996 derive_h (const struct GNUNET_CRYPTO_EccPublicSignKey *pub,
1001 struct GNUNET_HashCode hc;
1003 GNUNET_CRYPTO_kdf (&hc, sizeof (hc),
1004 "key-derivation", strlen ("key-derivation"),
1006 label, strlen (label),
1007 context, strlen (context),
1009 mpi_scan (&h, (unsigned char *) &hc, sizeof (hc));
1015 * Derive a private key from a given private key and a label.
1016 * Essentially calculates a private key 'd = H(l,P) * x mod n'
1017 * where n is the size of the ECC group and P is the public
1018 * key associated with the private key 'd'.
1020 * @param priv original private key
1021 * @param label label to use for key deriviation
1022 * @param context additional context to use for HKDF of 'h';
1023 * typically the name of the subsystem/application
1024 * @return derived private key
1026 struct GNUNET_CRYPTO_EccPrivateKey *
1027 GNUNET_CRYPTO_ecc_key_derive (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
1029 const char *context)
1031 struct GNUNET_CRYPTO_EccPublicSignKey pub;
1032 struct GNUNET_CRYPTO_EccPrivateKey *ret;
1039 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
1040 n = gcry_mpi_ec_get_mpi ("n", ctx, 1);
1041 GNUNET_CRYPTO_ecc_key_get_public_for_signature (priv, &pub);
1042 h = derive_h (&pub, label, context);
1043 mpi_scan (&x, priv->d, sizeof (priv->d));
1044 d = gcry_mpi_new (256);
1045 gcry_mpi_mulm (d, h, x, n);
1046 gcry_mpi_release (h);
1047 gcry_mpi_release (x);
1048 gcry_mpi_release (n);
1049 gcry_ctx_release (ctx);
1050 ret = GNUNET_new (struct GNUNET_CRYPTO_EccPrivateKey);
1051 mpi_print (ret->d, sizeof (ret->d), d);
1052 gcry_mpi_release (d);
1058 * Derive a public key from a given public key and a label.
1059 * Essentially calculates a public key 'V = H(l,P) * P'.
1061 * @param pub original public key
1062 * @param label label to use for key deriviation
1063 * @param context additional context to use for HKDF of 'h';
1064 * typically the name of the subsystem/application
1065 * @param result where to write the derived public key
1068 GNUNET_CRYPTO_ecc_public_key_derive (const struct GNUNET_CRYPTO_EccPublicSignKey *pub,
1070 const char *context,
1071 struct GNUNET_CRYPTO_EccPublicSignKey *result)
1082 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE));
1084 /* obtain point 'q' from original public key */
1085 mpi_scan (&q_x, pub->q_x, sizeof (pub->q_x));
1086 mpi_scan (&q_y, pub->q_y, sizeof (pub->q_y));
1088 q = gcry_mpi_point_new (0);
1089 gcry_mpi_point_set (q, q_x, q_y, GCRYMPI_CONST_ONE);
1090 gcry_mpi_release (q_x);
1091 gcry_mpi_release (q_y);
1093 /* calulcate h_mod_n = h % n */
1094 h = derive_h (pub, label, context);
1095 n = gcry_mpi_ec_get_mpi ("n", ctx, 1);
1096 h_mod_n = gcry_mpi_new (256);
1097 gcry_mpi_mod (h_mod_n, h, n);
1098 /* calculate v = h_mod_n * q */
1099 v = gcry_mpi_point_new (0);
1100 gcry_mpi_ec_mul (v, h_mod_n, q, ctx);
1101 gcry_mpi_release (h_mod_n);
1102 gcry_mpi_release (h);
1103 gcry_mpi_release (n);
1104 gcry_mpi_point_release (q);
1105 /* convert point 'v' to public key that we return */
1106 point_to_public_sign_key (v, ctx, result);
1107 gcry_mpi_point_release (v);
1108 gcry_ctx_release (ctx);
1112 /* end of crypto_ecc.c */