diff --git a/cipher/ecc-common.h b/cipher/ecc-common.h index 25c31112..edd14295 100644 --- a/cipher/ecc-common.h +++ b/cipher/ecc-common.h @@ -1,140 +1,142 @@ /* ecc-common.h - Declarations of common ECC code * Copyright (C) 2013 g10 Code GmbH * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . */ #ifndef GCRY_ECC_COMMON_H #define GCRY_ECC_COMMON_H /* Definition of a curve. */ typedef struct { enum gcry_mpi_ec_models model;/* The model descrinbing this curve. */ enum ecc_dialects dialect; /* The dialect used with the curve. */ gcry_mpi_t p; /* Prime specifying the field GF(p). */ gcry_mpi_t a; /* First coefficient of the Weierstrass equation. */ gcry_mpi_t b; /* Second coefficient of the Weierstrass equation. or d as used by Twisted Edwards curves. */ mpi_point_struct G; /* Base point (generator). */ gcry_mpi_t n; /* Order of G. */ unsigned int h; /* Cofactor. */ const char *name; /* Name of the curve or NULL. */ } elliptic_curve_t; /* Set the value from S into D. */ static inline void point_set (mpi_point_t d, mpi_point_t s) { mpi_set (d->x, s->x); mpi_set (d->y, s->y); mpi_set (d->z, s->z); } #define point_init(a) _gcry_mpi_point_init ((a)) #define point_free(a) _gcry_mpi_point_free_parts ((a)) /*-- ecc-curves.c --*/ gpg_err_code_t _gcry_ecc_fill_in_curve (unsigned int nbits, const char *name, elliptic_curve_t *curve, unsigned int *r_nbits); gpg_err_code_t _gcry_ecc_update_curve_param (const char *name, enum gcry_mpi_ec_models *model, enum ecc_dialects *dialect, gcry_mpi_t *p, gcry_mpi_t *a, gcry_mpi_t *b, gcry_mpi_t *g, gcry_mpi_t *n); const char *_gcry_ecc_get_curve (gcry_sexp_t keyparms, int iterator, unsigned int *r_nbits); gcry_sexp_t _gcry_ecc_get_param_sexp (const char *name); /*-- ecc-misc.c --*/ void _gcry_ecc_curve_free (elliptic_curve_t *E); elliptic_curve_t _gcry_ecc_curve_copy (elliptic_curve_t E); const char *_gcry_ecc_model2str (enum gcry_mpi_ec_models model); const char *_gcry_ecc_dialect2str (enum ecc_dialects dialect); +unsigned char *_gcry_ecc_ec2os_buf (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t p, + unsigned int *r_length); gcry_mpi_t _gcry_ecc_ec2os (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t p); mpi_point_t _gcry_ecc_compute_public (mpi_point_t Q, mpi_ec_t ec); gpg_err_code_t _gcry_ecc_mont_encodepoint (gcry_mpi_t x, unsigned int nbits, int with_prefix, unsigned char **r_buffer, unsigned int *r_buflen); /*-- ecc.c --*/ /*-- ecc-ecdsa.c --*/ gpg_err_code_t _gcry_ecc_ecdsa_sign (gcry_mpi_t input, mpi_ec_t ec, gcry_mpi_t r, gcry_mpi_t s, int flags, int hashalgo); gpg_err_code_t _gcry_ecc_ecdsa_verify (gcry_mpi_t input, mpi_ec_t ec, gcry_mpi_t r, gcry_mpi_t s); /*-- ecc-eddsa.c --*/ gpg_err_code_t _gcry_ecc_eddsa_recover_x (gcry_mpi_t x, gcry_mpi_t y, int sign, mpi_ec_t ec); gpg_err_code_t _gcry_ecc_eddsa_encodepoint (mpi_point_t point, mpi_ec_t ctx, gcry_mpi_t x, gcry_mpi_t y, int with_prefix, unsigned char **r_buffer, unsigned int *r_buflen); gpg_err_code_t _gcry_ecc_eddsa_ensure_compact (gcry_mpi_t value, unsigned int nbits); gpg_err_code_t _gcry_ecc_eddsa_compute_h_d (unsigned char **r_digest, mpi_ec_t ec); gpg_err_code_t _gcry_ecc_eddsa_genkey (mpi_ec_t ec, int flags); gpg_err_code_t _gcry_ecc_eddsa_sign (gcry_mpi_t input, mpi_ec_t ec, gcry_mpi_t r_r, gcry_mpi_t s, struct pk_encoding_ctx *ctx); gpg_err_code_t _gcry_ecc_eddsa_verify (gcry_mpi_t input, mpi_ec_t ec, gcry_mpi_t r, gcry_mpi_t s, struct pk_encoding_ctx *ctx); void reverse_buffer (unsigned char *buffer, unsigned int length); /*-- ecc-gost.c --*/ gpg_err_code_t _gcry_ecc_gost_sign (gcry_mpi_t input, mpi_ec_t ec, gcry_mpi_t r, gcry_mpi_t s); gpg_err_code_t _gcry_ecc_gost_verify (gcry_mpi_t input, mpi_ec_t ec, gcry_mpi_t r, gcry_mpi_t s); /*-- ecc-sm2.c --*/ gpg_err_code_t _gcry_ecc_sm2_encrypt (gcry_sexp_t *r_ciph, gcry_mpi_t input, mpi_ec_t ec); gpg_err_code_t _gcry_ecc_sm2_decrypt (gcry_sexp_t *r_plain, gcry_sexp_t data_list, mpi_ec_t ec); gpg_err_code_t _gcry_ecc_sm2_sign (gcry_mpi_t input, mpi_ec_t ec, gcry_mpi_t r, gcry_mpi_t s, int flags, int hashalgo); gpg_err_code_t _gcry_ecc_sm2_verify (gcry_mpi_t input, mpi_ec_t ec, gcry_mpi_t r, gcry_mpi_t s); #endif /*GCRY_ECC_COMMON_H*/ diff --git a/cipher/ecc-misc.c b/cipher/ecc-misc.c index 6470a83b..d4241190 100644 --- a/cipher/ecc-misc.c +++ b/cipher/ecc-misc.c @@ -1,438 +1,453 @@ /* ecc-misc.c - Elliptic Curve miscellaneous functions * Copyright (C) 2007, 2008, 2010, 2011 Free Software Foundation, Inc. * Copyright (C) 2013 g10 Code GmbH * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . */ #include #include #include #include #include #include "g10lib.h" #include "mpi.h" #include "cipher.h" #include "context.h" #include "ec-context.h" #include "ecc-common.h" /* * Release a curve object. */ void _gcry_ecc_curve_free (elliptic_curve_t *E) { mpi_free (E->p); E->p = NULL; mpi_free (E->a); E->a = NULL; mpi_free (E->b); E->b = NULL; _gcry_mpi_point_free_parts (&E->G); mpi_free (E->n); E->n = NULL; } /* * Return a copy of a curve object. */ elliptic_curve_t _gcry_ecc_curve_copy (elliptic_curve_t E) { elliptic_curve_t R; R.model = E.model; R.dialect = E.dialect; R.name = E.name; R.p = mpi_copy (E.p); R.a = mpi_copy (E.a); R.b = mpi_copy (E.b); _gcry_mpi_point_init (&R.G); point_set (&R.G, &E.G); R.n = mpi_copy (E.n); R.h = E.h; return R; } /* * Return a description of the curve model. */ const char * _gcry_ecc_model2str (enum gcry_mpi_ec_models model) { const char *str = "?"; switch (model) { case MPI_EC_WEIERSTRASS: str = "Weierstrass"; break; case MPI_EC_MONTGOMERY: str = "Montgomery"; break; case MPI_EC_EDWARDS: str = "Edwards"; break; } return str; } /* * Return a description of the curve dialect. */ const char * _gcry_ecc_dialect2str (enum ecc_dialects dialect) { const char *str = "?"; switch (dialect) { case ECC_DIALECT_STANDARD: str = "Standard"; break; case ECC_DIALECT_ED25519: str = "Ed25519"; break; case ECC_DIALECT_SAFECURVE: str = "SafeCurve"; break; } return str; } -gcry_mpi_t -_gcry_ecc_ec2os (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t p) +/* Return an uncompressed point (X,Y) in P as a malloced buffer with + * its byte length stored at R_LENGTH. May not be used for sensitive + * data. */ +unsigned char * +_gcry_ecc_ec2os_buf (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t p, + unsigned int *r_length) { gpg_err_code_t rc; int pbytes = (mpi_get_nbits (p)+7)/8; size_t n; unsigned char *buf, *ptr; buf = xmalloc ( 1 + 2*pbytes ); *buf = 04; /* Uncompressed point. */ ptr = buf+1; rc = _gcry_mpi_print (GCRYMPI_FMT_USG, ptr, pbytes, &n, x); if (rc) log_fatal ("mpi_print failed: %s\n", gpg_strerror (rc)); if (n < pbytes) { memmove (ptr+(pbytes-n), ptr, n); memset (ptr, 0, (pbytes-n)); } ptr += pbytes; rc = _gcry_mpi_print (GCRYMPI_FMT_USG, ptr, pbytes, &n, y); if (rc) log_fatal ("mpi_print failed: %s\n", gpg_strerror (rc)); if (n < pbytes) { memmove (ptr+(pbytes-n), ptr, n); memset (ptr, 0, (pbytes-n)); } - return mpi_set_opaque (NULL, buf, (1+2*pbytes)*8); + *r_length = 1 + 2*pbytes; + return buf; } +gcry_mpi_t +_gcry_ecc_ec2os (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t p) +{ + unsigned char *buf; + unsigned int buflen; + + buf = _gcry_ecc_ec2os_buf (x, y, p, &buflen); + return mpi_set_opaque (NULL, buf, 8*buflen); +} + /* Convert POINT into affine coordinates using the context CTX and return a newly allocated MPI. If the conversion is not possible NULL is returned. This function won't print an error message. */ gcry_mpi_t _gcry_mpi_ec_ec2os (gcry_mpi_point_t point, mpi_ec_t ec) { gcry_mpi_t g_x, g_y, result; g_x = mpi_new (0); g_y = mpi_new (0); if (_gcry_mpi_ec_get_affine (g_x, g_y, point, ec)) result = NULL; else result = _gcry_ecc_ec2os (g_x, g_y, ec->p); mpi_free (g_x); mpi_free (g_y); return result; } /* Decode octet string in VALUE into RESULT, in the format defined by SEC 1. RESULT must have been initialized and is set on success to the point given by VALUE. */ gpg_err_code_t _gcry_ecc_sec_decodepoint (gcry_mpi_t value, mpi_ec_t ec, mpi_point_t result) { gpg_err_code_t rc; size_t n; const unsigned char *buf; unsigned char *buf_memory; gcry_mpi_t x, y; if (mpi_is_opaque (value)) { unsigned int nbits; buf = mpi_get_opaque (value, &nbits); if (!buf) return GPG_ERR_INV_OBJ; n = (nbits + 7)/8; buf_memory = NULL; } else { n = (mpi_get_nbits (value)+7)/8; buf_memory = xmalloc (n); rc = _gcry_mpi_print (GCRYMPI_FMT_USG, buf_memory, n, &n, value); if (rc) { xfree (buf_memory); return rc; } buf = buf_memory; } if (n < 1) { xfree (buf_memory); return GPG_ERR_INV_OBJ; } if (*buf == 2 || *buf == 3) { gcry_mpi_t x3; gcry_mpi_t t; gcry_mpi_t p1_4; int y_bit = (*buf == 3); if (!mpi_test_bit (ec->p, 1)) { xfree (buf_memory); return GPG_ERR_NOT_IMPLEMENTED; /* No support for point compression. */ } n = n - 1; rc = _gcry_mpi_scan (&x, GCRYMPI_FMT_USG, buf+1, n, NULL); xfree (buf_memory); if (rc) return rc; /* * Recover Y. The Weierstrass curve: y^2 = x^3 + a*x + b */ x3 = mpi_new (0); t = mpi_new (0); p1_4 = mpi_new (0); y = mpi_new (0); /* Compute right hand side. */ mpi_powm (x3, x, mpi_const (MPI_C_THREE), ec->p); mpi_mul (t, ec->a, x); mpi_mod (t, t, ec->p); mpi_add (t, t, ec->b); mpi_mod (t, t, ec->p); mpi_add (t, t, x3); mpi_mod (t, t, ec->p); /* * When p mod 4 = 3, modular square root of A can be computed by * A^((p+1)/4) mod p */ /* Compute (p+1)/4 into p1_4 */ mpi_rshift (p1_4, ec->p, 2); _gcry_mpi_add_ui (p1_4, p1_4, 1); mpi_powm (y, t, p1_4, ec->p); if (y_bit != mpi_test_bit (y, 0)) mpi_sub (y, ec->p, y); mpi_free (p1_4); mpi_free (t); mpi_free (x3); } else if (*buf == 4) { if ( ((n-1)%2) ) { xfree (buf_memory); return GPG_ERR_INV_OBJ; } n = (n-1)/2; rc = _gcry_mpi_scan (&x, GCRYMPI_FMT_USG, buf+1, n, NULL); if (rc) { xfree (buf_memory); return rc; } rc = _gcry_mpi_scan (&y, GCRYMPI_FMT_USG, buf+1+n, n, NULL); xfree (buf_memory); if (rc) { mpi_free (x); return rc; } } else { xfree (buf_memory); return GPG_ERR_INV_OBJ; } mpi_set (result->x, x); mpi_set (result->y, y); mpi_set_ui (result->z, 1); mpi_free (x); mpi_free (y); return 0; } /* Compute the public key from the the context EC. Obviously a requirement is that the secret key is available in EC. On success Q is returned; on error NULL. If Q is NULL a newly allocated point is returned. If G or D are given they override the values taken from EC. */ mpi_point_t _gcry_ecc_compute_public (mpi_point_t Q, mpi_ec_t ec) { if (!ec->d || !ec->G || !ec->p || !ec->a) return NULL; if (ec->model == MPI_EC_EDWARDS && !ec->b) return NULL; if ((ec->dialect == ECC_DIALECT_ED25519 && (ec->flags & PUBKEY_FLAG_EDDSA)) || (ec->model == MPI_EC_EDWARDS && ec->dialect == ECC_DIALECT_SAFECURVE)) { gcry_mpi_t a; unsigned char *digest; if (_gcry_ecc_eddsa_compute_h_d (&digest, ec)) return NULL; a = mpi_snew (0); _gcry_mpi_set_buffer (a, digest, 32, 0); xfree (digest); /* And finally the public key. */ if (!Q) Q = mpi_point_new (0); if (Q) _gcry_mpi_ec_mul_point (Q, a, ec->G, ec); mpi_free (a); } else { if (!Q) Q = mpi_point_new (0); if (Q) _gcry_mpi_ec_mul_point (Q, ec->d, ec->G, ec); } return Q; } gpg_err_code_t _gcry_ecc_mont_encodepoint (gcry_mpi_t x, unsigned int nbits, int with_prefix, unsigned char **r_buffer, unsigned int *r_buflen) { unsigned char *rawmpi; unsigned int rawmpilen; rawmpi = _gcry_mpi_get_buffer_extra (x, (nbits+7)/8, with_prefix? -1 : 0, &rawmpilen, NULL); if (rawmpi == NULL) return gpg_err_code_from_syserror (); if (with_prefix) { rawmpi[0] = 0x40; rawmpilen++; } *r_buffer = rawmpi; *r_buflen = rawmpilen; return 0; } gpg_err_code_t _gcry_ecc_mont_decodepoint (gcry_mpi_t pk, mpi_ec_t ec, mpi_point_t result) { unsigned char *rawmpi; unsigned int rawmpilen; unsigned int nbytes = (ec->nbits+7)/8; /* * It is not reliable to assume that the first byte of 0x40 * means the prefix. * * For newer implementation, it is reliable since we always put * 0x40 for x-only coordinate. * * For data by older implementation (non-released development * version in 2015), there is no 0x40 prefix added. * * So, it is possible to have shorter length of data when it was * handled as MPI, removing preceding zeros. * * Besides, when data was parsed as MPI, we might have 0x00 * prefix (when the MSB in the first byte is set). */ if (mpi_is_opaque (pk)) { const unsigned char *buf; unsigned char *p; buf = mpi_get_opaque (pk, &rawmpilen); if (!buf) return GPG_ERR_INV_OBJ; rawmpilen = (rawmpilen + 7)/8; if (rawmpilen > nbytes && (buf[0] == 0x00 || buf[0] == 0x40)) { rawmpilen--; buf++; } rawmpi = xtrymalloc (nbytes); if (!rawmpi) return gpg_err_code_from_syserror (); p = rawmpi + rawmpilen; while (p > rawmpi) *--p = *buf++; if (rawmpilen < nbytes) memset (rawmpi + nbytes - rawmpilen, 0, nbytes - rawmpilen); } else { rawmpi = _gcry_mpi_get_buffer (pk, nbytes, &rawmpilen, NULL); if (!rawmpi) return gpg_err_code_from_syserror (); /* * When we have the prefix (0x40 or 0x00), it comes at the end, * since it is taken by _gcry_mpi_get_buffer with little endian. * Just setting RAWMPILEN to NBYTES is enough in this case. * Othewise, RAWMPILEN is NBYTES already. */ rawmpilen = nbytes; } if ((ec->nbits % 8)) rawmpi[0] &= (1 << (ec->nbits % 8)) - 1; _gcry_mpi_set_buffer (result->x, rawmpi, rawmpilen, 0); xfree (rawmpi); mpi_set_ui (result->z, 1); return 0; } diff --git a/cipher/ecc.c b/cipher/ecc.c index 5d8c7607..db200738 100644 --- a/cipher/ecc.c +++ b/cipher/ecc.c @@ -1,1779 +1,1871 @@ /* ecc.c - Elliptic Curve Cryptography * Copyright (C) 2007, 2008, 2010, 2011 Free Software Foundation, Inc. * Copyright (C) 2013, 2015 g10 Code GmbH * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . */ /* This code is originally based on the Patch 0.1.6 for the gnupg 1.4.x branch as retrieved on 2007-03-21 from http://www.calcurco.cat/eccGnuPG/src/gnupg-1.4.6-ecc0.2.0beta1.diff.bz2 The original authors are: Written by Sergi Blanch i Torne , Ramiro Moreno Chiral Maintainers Sergi Blanch i Torne Ramiro Moreno Chiral Mikael Mylnikov (mmr) For use in Libgcrypt the code has been heavily modified and cleaned up. In fact there is not much left of the originally code except for some variable names and the text book implementaion of the sign and verification algorithms. The arithmetic functions have entirely been rewritten and moved to mpi/ec.c. ECDH encrypt and decrypt code written by Andrey Jivsov. */ /* TODO: - In mpi/ec.c we use mpi_powm for x^2 mod p: Either implement a special case in mpi_powm or check whether mpi_mulm is faster. */ #include #include #include #include #include #include "g10lib.h" #include "mpi.h" #include "cipher.h" #include "context.h" #include "ec-context.h" #include "pubkey-internal.h" #include "ecc-common.h" static const char *ecc_names[] = { "ecc", "ecdsa", "ecdh", "eddsa", "gost", "sm2", NULL, }; /* Sample NIST P-256 key from RFC 6979 A.2.5 */ static const char sample_public_key_secp256[] = "(public-key" " (ecc" " (curve secp256r1)" " (q #04" /**/ "60FED4BA255A9D31C961EB74C6356D68C049B8923B61FA6CE669622E60F29FB6" /**/ "7903FE1008B8BC99A41AE9E95628BC64F2F1B20C2D7E9F5177A3C294D4462299#)))"; static const char sample_secret_key_secp256[] = "(private-key" " (ecc" " (curve secp256r1)" " (d #C9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721#)" " (q #04" /**/ "60FED4BA255A9D31C961EB74C6356D68C049B8923B61FA6CE669622E60F29FB6" /**/ "7903FE1008B8BC99A41AE9E95628BC64F2F1B20C2D7E9F5177A3C294D4462299#)))"; /* Registered progress function and its callback value. */ static void (*progress_cb) (void *, const char*, int, int, int); static void *progress_cb_data; /* Local prototypes. */ static void test_keys (mpi_ec_t ec, unsigned int nbits); static void test_ecdh_only_keys (mpi_ec_t ec, unsigned int nbits, int flags); static unsigned int ecc_get_nbits (gcry_sexp_t parms); void _gcry_register_pk_ecc_progress (void (*cb) (void *, const char *, int, int, int), void *cb_data) { progress_cb = cb; progress_cb_data = cb_data; } /* static void */ /* progress (int c) */ /* { */ /* if (progress_cb) */ /* progress_cb (progress_cb_data, "pk_ecc", c, 0, 0); */ /* } */ /** * nist_generate_key - Standard version of the ECC key generation. * @ec: Elliptic curve computation context. * @flags: Flags controlling aspects of the creation. * @r_x: On success this receives an allocated MPI with the affine * x-coordinate of the poblic key. On error NULL is stored. * @r_y: Ditto for the y-coordinate. * * Return: An error code. * * The @flags bits used by this function are %PUBKEY_FLAG_TRANSIENT to * use a faster RNG, and %PUBKEY_FLAG_NO_KEYTEST to skip the assertion * that the key works as expected. * * FIXME: Check whether N is needed. */ static gpg_err_code_t nist_generate_key (mpi_ec_t ec, int flags, gcry_mpi_t *r_x, gcry_mpi_t *r_y) { mpi_point_struct Q; gcry_random_level_t random_level; gcry_mpi_t x, y; const unsigned int pbits = ec->nbits; point_init (&Q); if ((flags & PUBKEY_FLAG_TRANSIENT_KEY)) random_level = GCRY_STRONG_RANDOM; else random_level = GCRY_VERY_STRONG_RANDOM; /* Generate a secret. */ if (ec->dialect == ECC_DIALECT_ED25519 || ec->dialect == ECC_DIALECT_SAFECURVE || (flags & PUBKEY_FLAG_DJB_TWEAK)) { char *rndbuf; int len = (pbits+7)/8; rndbuf = _gcry_random_bytes_secure (len, random_level); if (ec->dialect == ECC_DIALECT_SAFECURVE) ec->d = mpi_set_opaque (NULL, rndbuf, len*8); else { ec->d = mpi_snew (pbits); if ((pbits % 8)) rndbuf[0] &= (1 << (pbits % 8)) - 1; rndbuf[0] |= (1 << ((pbits + 7) % 8)); rndbuf[len-1] &= (256 - ec->h); _gcry_mpi_set_buffer (ec->d, rndbuf, len, 0); xfree (rndbuf); } } else ec->d = _gcry_dsa_gen_k (ec->n, random_level); /* Compute Q. */ _gcry_mpi_ec_mul_point (&Q, ec->d, ec->G, ec); x = mpi_new (pbits); if (r_y == NULL) y = NULL; else y = mpi_new (pbits); if (_gcry_mpi_ec_get_affine (x, y, &Q, ec)) log_fatal ("ecgen: Failed to get affine coordinates for %s\n", "Q"); /* We want the Q=(x,y) be a "compliant key" in terms of the * http://tools.ietf.org/html/draft-jivsov-ecc-compact, which simply * means that we choose either Q=(x,y) or -Q=(x,p-y) such that we * end up with the min(y,p-y) as the y coordinate. Such a public * key allows the most efficient compression: y can simply be * dropped because we know that it's a minimum of the two * possibilities without any loss of security. Note that we don't * do that for Ed25519 so that we do not violate the special * construction of the secret key. */ if (r_y == NULL || ec->dialect == ECC_DIALECT_ED25519) ec->Q = mpi_point_set (NULL, Q.x, Q.y, Q.z); else { gcry_mpi_t negative; negative = mpi_new (pbits); if (ec->model == MPI_EC_WEIERSTRASS) mpi_sub (negative, ec->p, y); /* negative = p - y */ else mpi_sub (negative, ec->p, x); /* negative = p - x */ if (mpi_cmp (negative, y) < 0) /* p - y < p */ { /* We need to end up with -Q; this assures that new Q's y is the smallest one */ if (ec->model == MPI_EC_WEIERSTRASS) { mpi_free (y); y = negative; } else { mpi_free (x); x = negative; } mpi_sub (ec->d, ec->n, ec->d); /* d = order - d */ ec->Q = mpi_point_set (NULL, x, y, mpi_const (MPI_C_ONE)); if (DBG_CIPHER) log_debug ("ecgen converted Q to a compliant point\n"); } else /* p - y >= p */ { /* No change is needed exactly 50% of the time: just copy. */ mpi_free (negative); ec->Q = mpi_point_set (NULL, Q.x, Q.y, Q.z); if (DBG_CIPHER) log_debug ("ecgen didn't need to convert Q to a compliant point\n"); } } *r_x = x; if (r_y) *r_y = y; point_free (&Q); /* Now we can test our keys (this should never fail!). */ if ((flags & PUBKEY_FLAG_NO_KEYTEST)) ; /* User requested to skip the test. */ else if (ec->model == MPI_EC_MONTGOMERY) test_ecdh_only_keys (ec, ec->nbits - 63, flags); else test_keys (ec, ec->nbits - 64); return 0; } /* * To verify correct skey it use a random information. * First, encrypt and decrypt this dummy value, * test if the information is recuperated. * Second, test with the sign and verify functions. */ static void test_keys (mpi_ec_t ec, unsigned int nbits) { gcry_mpi_t test = mpi_new (nbits); mpi_point_struct R_; gcry_mpi_t c = mpi_new (nbits); gcry_mpi_t out = mpi_new (nbits); gcry_mpi_t r = mpi_new (nbits); gcry_mpi_t s = mpi_new (nbits); if (DBG_CIPHER) log_debug ("Testing key.\n"); point_init (&R_); _gcry_mpi_randomize (test, nbits, GCRY_WEAK_RANDOM); if (_gcry_ecc_ecdsa_sign (test, ec, r, s, 0, 0) ) log_fatal ("ECDSA operation: sign failed\n"); if (_gcry_ecc_ecdsa_verify (test, ec, r, s)) { log_fatal ("ECDSA operation: sign, verify failed\n"); } if (DBG_CIPHER) log_debug ("ECDSA operation: sign, verify ok.\n"); point_free (&R_); mpi_free (s); mpi_free (r); mpi_free (out); mpi_free (c); mpi_free (test); } static void test_ecdh_only_keys (mpi_ec_t ec, unsigned int nbits, int flags) { gcry_mpi_t test; mpi_point_struct R_; gcry_mpi_t x0, x1; if (DBG_CIPHER) log_debug ("Testing ECDH only key.\n"); point_init (&R_); if (ec->dialect == ECC_DIALECT_SAFECURVE || (flags & PUBKEY_FLAG_DJB_TWEAK)) { char *rndbuf; const unsigned int pbits = ec->nbits; int len = (pbits+7)/8; rndbuf = _gcry_random_bytes (len, GCRY_WEAK_RANDOM); if (ec->dialect == ECC_DIALECT_SAFECURVE) test = mpi_set_opaque (NULL, rndbuf, len*8); else { test = mpi_new (pbits); if ((pbits % 8)) rndbuf[0] &= (1 << (pbits % 8)) - 1; rndbuf[0] |= (1 << ((pbits + 7) % 8)); rndbuf[len-1] &= (256 - ec->h); _gcry_mpi_set_buffer (test, rndbuf, len, 0); xfree (rndbuf); } } else { test = mpi_new (nbits); _gcry_mpi_randomize (test, nbits, GCRY_WEAK_RANDOM); } x0 = mpi_new (0); x1 = mpi_new (0); /* R_ = hkQ <=> R_ = hkdG */ _gcry_mpi_ec_mul_point (&R_, test, ec->Q, ec); if (ec->dialect == ECC_DIALECT_STANDARD && !(flags & PUBKEY_FLAG_DJB_TWEAK)) _gcry_mpi_ec_mul_point (&R_, _gcry_mpi_get_const (ec->h), &R_, ec); if (_gcry_mpi_ec_get_affine (x0, NULL, &R_, ec)) log_fatal ("ecdh: Failed to get affine coordinates for hkQ\n"); _gcry_mpi_ec_mul_point (&R_, test, ec->G, ec); _gcry_mpi_ec_mul_point (&R_, ec->d, &R_, ec); /* R_ = hdkG */ if (ec->dialect == ECC_DIALECT_STANDARD && !(flags & PUBKEY_FLAG_DJB_TWEAK)) _gcry_mpi_ec_mul_point (&R_, _gcry_mpi_get_const (ec->h), &R_, ec); if (_gcry_mpi_ec_get_affine (x1, NULL, &R_, ec)) log_fatal ("ecdh: Failed to get affine coordinates for hdkG\n"); if (mpi_cmp (x0, x1)) { log_fatal ("ECDH test failed.\n"); } mpi_free (x0); mpi_free (x1); point_free (&R_); mpi_free (test); } /* * To check the validity of the value, recalculate the correspondence * between the public value and the secret one. */ static int check_secret_key (mpi_ec_t ec, int flags) { int rc = 1; mpi_point_struct Q; gcry_mpi_t x1, y1; gcry_mpi_t x2 = NULL; gcry_mpi_t y2 = NULL; point_init (&Q); x1 = mpi_new (0); if (ec->model == MPI_EC_MONTGOMERY) y1 = NULL; else y1 = mpi_new (0); /* G in E(F_p) */ if (!_gcry_mpi_ec_curve_point (ec->G, ec)) { if (DBG_CIPHER) log_debug ("Bad check: Point 'G' does not belong to curve 'E'!\n"); goto leave; } /* G != PaI */ if (!mpi_cmp_ui (ec->G->z, 0)) { if (DBG_CIPHER) log_debug ("Bad check: 'G' cannot be Point at Infinity!\n"); goto leave; } /* Check order of curve. */ if (ec->dialect == ECC_DIALECT_STANDARD && !(flags & PUBKEY_FLAG_DJB_TWEAK)) { _gcry_mpi_ec_mul_point (&Q, ec->n, ec->G, ec); if (mpi_cmp_ui (Q.z, 0)) { if (DBG_CIPHER) log_debug ("check_secret_key: E is not a curve of order n\n"); goto leave; } } /* Pubkey cannot be PaI */ if (!mpi_cmp_ui (ec->Q->z, 0)) { if (DBG_CIPHER) log_debug ("Bad check: Q can not be a Point at Infinity!\n"); goto leave; } /* pubkey = [d]G over E */ if (!_gcry_ecc_compute_public (&Q, ec)) { if (DBG_CIPHER) log_debug ("Bad check: computation of dG failed\n"); goto leave; } if (_gcry_mpi_ec_get_affine (x1, y1, &Q, ec)) { if (DBG_CIPHER) log_debug ("Bad check: Q can not be a Point at Infinity!\n"); goto leave; } if ((flags & PUBKEY_FLAG_EDDSA) || (ec->model == MPI_EC_EDWARDS && ec->dialect == ECC_DIALECT_SAFECURVE)) ; /* Fixme: EdDSA is special. */ else if (!mpi_cmp_ui (ec->Q->z, 1)) { /* Fast path if Q is already in affine coordinates. */ if (mpi_cmp (x1, ec->Q->x) || (y1 && mpi_cmp (y1, ec->Q->y))) { if (DBG_CIPHER) log_debug ("Bad check: There is NO correspondence between 'd' and 'Q'!\n"); goto leave; } } else { x2 = mpi_new (0); y2 = mpi_new (0); if (_gcry_mpi_ec_get_affine (x2, y2, ec->Q, ec)) { if (DBG_CIPHER) log_debug ("Bad check: Q can not be a Point at Infinity!\n"); goto leave; } if (mpi_cmp (x1, x2) || mpi_cmp (y1, y2)) { if (DBG_CIPHER) log_debug ("Bad check: There is NO correspondence between 'd' and 'Q'!\n"); goto leave; } } rc = 0; /* Okay. */ leave: mpi_free (x2); mpi_free (x1); mpi_free (y1); mpi_free (y2); point_free (&Q); return rc; } /********************************************* ************** interface ****************** *********************************************/ static gcry_err_code_t ecc_generate (const gcry_sexp_t genparms, gcry_sexp_t *r_skey) { gpg_err_code_t rc; gcry_mpi_t Gx = NULL; gcry_mpi_t Gy = NULL; gcry_mpi_t Qx = NULL; gcry_mpi_t Qy = NULL; mpi_ec_t ec = NULL; gcry_sexp_t curve_info = NULL; gcry_sexp_t curve_flags = NULL; gcry_mpi_t base = NULL; gcry_mpi_t public = NULL; int flags = 0; rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecgen curve", genparms, NULL); if (rc) goto leave; if ((flags & PUBKEY_FLAG_EDDSA) || (ec->model == MPI_EC_EDWARDS && ec->dialect == ECC_DIALECT_SAFECURVE)) rc = _gcry_ecc_eddsa_genkey (ec, flags); else if (ec->model == MPI_EC_MONTGOMERY) rc = nist_generate_key (ec, flags, &Qx, NULL); else rc = nist_generate_key (ec, flags, &Qx, &Qy); if (rc) goto leave; /* Copy data to the result. */ Gx = mpi_new (0); Gy = mpi_new (0); if (ec->model != MPI_EC_MONTGOMERY) { if (_gcry_mpi_ec_get_affine (Gx, Gy, ec->G, ec)) log_fatal ("ecgen: Failed to get affine coordinates for %s\n", "G"); base = _gcry_ecc_ec2os (Gx, Gy, ec->p); } if (((ec->dialect == ECC_DIALECT_SAFECURVE && ec->model == MPI_EC_EDWARDS) || ec->dialect == ECC_DIALECT_ED25519 || ec->model == MPI_EC_MONTGOMERY) && !(flags & PUBKEY_FLAG_NOCOMP)) { unsigned char *encpk; unsigned int encpklen; if (ec->model == MPI_EC_MONTGOMERY) rc = _gcry_ecc_mont_encodepoint (Qx, ec->nbits, ec->dialect != ECC_DIALECT_SAFECURVE, &encpk, &encpklen); else /* (Gx and Gy are used as scratch variables) */ rc = _gcry_ecc_eddsa_encodepoint (ec->Q, ec, Gx, Gy, (ec->dialect != ECC_DIALECT_SAFECURVE && !!(flags & PUBKEY_FLAG_COMP)), &encpk, &encpklen); if (rc) goto leave; public = mpi_new (0); mpi_set_opaque (public, encpk, encpklen*8); } else { if (!Qx) { /* This is the case for a key from _gcry_ecc_eddsa_generate with no compression. */ Qx = mpi_new (0); Qy = mpi_new (0); if (_gcry_mpi_ec_get_affine (Qx, Qy, ec->Q, ec)) log_fatal ("ecgen: Failed to get affine coordinates for %s\n", "Q"); } public = _gcry_ecc_ec2os (Qx, Qy, ec->p); } if (ec->name) { rc = sexp_build (&curve_info, NULL, "(curve %s)", ec->name); if (rc) goto leave; } if ((flags & PUBKEY_FLAG_PARAM) || (flags & PUBKEY_FLAG_EDDSA) || (flags & PUBKEY_FLAG_DJB_TWEAK)) { rc = sexp_build (&curve_flags, NULL, ((flags & PUBKEY_FLAG_PARAM) && (flags & PUBKEY_FLAG_EDDSA))? "(flags param eddsa)" : ((flags & PUBKEY_FLAG_PARAM) && (flags & PUBKEY_FLAG_DJB_TWEAK))? "(flags param djb-tweak)" : ((flags & PUBKEY_FLAG_PARAM))? "(flags param)" : ((flags & PUBKEY_FLAG_EDDSA))? "(flags eddsa)" : "(flags djb-tweak)" ); if (rc) goto leave; } if ((flags & PUBKEY_FLAG_PARAM) && ec->name) rc = sexp_build (r_skey, NULL, "(key-data" " (public-key" " (ecc%S%S(p%m)(a%m)(b%m)(g%m)(n%m)(h%u)(q%m)))" " (private-key" " (ecc%S%S(p%m)(a%m)(b%m)(g%m)(n%m)(h%u)(q%m)(d%m)))" " )", curve_info, curve_flags, ec->p, ec->a, ec->b, base, ec->n, ec->h, public, curve_info, curve_flags, ec->p, ec->a, ec->b, base, ec->n, ec->h, public, ec->d); else rc = sexp_build (r_skey, NULL, "(key-data" " (public-key" " (ecc%S%S(q%m)))" " (private-key" " (ecc%S%S(q%m)(d%m)))" " )", curve_info, curve_flags, public, curve_info, curve_flags, public, ec->d); if (rc) goto leave; if (DBG_CIPHER) { log_printmpi ("ecgen result p", ec->p); log_printmpi ("ecgen result a", ec->a); log_printmpi ("ecgen result b", ec->b); log_printmpi ("ecgen result G", base); log_printmpi ("ecgen result n", ec->n); log_debug ("ecgen result h:+%02x\n", ec->h); log_printmpi ("ecgen result Q", public); log_printmpi ("ecgen result d", ec->d); if ((flags & PUBKEY_FLAG_EDDSA)) log_debug ("ecgen result using Ed25519+EdDSA\n"); } leave: mpi_free (public); mpi_free (base); mpi_free (Gx); mpi_free (Gy); mpi_free (Qx); mpi_free (Qy); _gcry_mpi_ec_free (ec); sexp_release (curve_flags); sexp_release (curve_info); return rc; } static gcry_err_code_t ecc_check_secret_key (gcry_sexp_t keyparms) { gcry_err_code_t rc; int flags = 0; mpi_ec_t ec = NULL; /* * Extract the key. */ rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_testkey", keyparms, NULL); if (rc) goto leave; if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n || !ec->Q || !ec->d) { rc = GPG_ERR_NO_OBJ; goto leave; } if (check_secret_key (ec, flags)) rc = GPG_ERR_BAD_SECKEY; leave: _gcry_mpi_ec_free (ec); if (DBG_CIPHER) log_debug ("ecc_testkey => %s\n", gpg_strerror (rc)); return rc; } static gcry_err_code_t ecc_sign (gcry_sexp_t *r_sig, gcry_sexp_t s_data, gcry_sexp_t keyparms) { gcry_err_code_t rc; struct pk_encoding_ctx ctx; gcry_mpi_t data = NULL; gcry_mpi_t sig_r = NULL; gcry_mpi_t sig_s = NULL; mpi_ec_t ec = NULL; int flags = 0; _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_SIGN, 0); /* * Extract the key. */ rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_sign", keyparms, NULL); if (rc) goto leave; if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n || !ec->d) { rc = GPG_ERR_NO_OBJ; goto leave; } ctx.flags |= flags; if (ec->model == MPI_EC_EDWARDS && ec->dialect == ECC_DIALECT_SAFECURVE) ctx.flags |= PUBKEY_FLAG_EDDSA; /* Clear hash algo for EdDSA. */ if ((ctx.flags & PUBKEY_FLAG_EDDSA)) ctx.hash_algo = GCRY_MD_NONE; /* Extract the data. */ rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx); if (rc) goto leave; if (DBG_CIPHER) log_mpidump ("ecc_sign data", data); /* Hash algo is determined by curve in EdDSA. Fill it if not specified. */ if ((ctx.flags & PUBKEY_FLAG_EDDSA) && !ctx.hash_algo) { if (ec->dialect == ECC_DIALECT_ED25519) ctx.hash_algo = GCRY_MD_SHA512; else if (ec->dialect == ECC_DIALECT_SAFECURVE) ctx.hash_algo = GCRY_MD_SHAKE256; } sig_r = mpi_new (0); sig_s = mpi_new (0); if ((ctx.flags & PUBKEY_FLAG_EDDSA)) { /* EdDSA requires the public key. */ rc = _gcry_ecc_eddsa_sign (data, ec, sig_r, sig_s, &ctx); if (!rc) rc = sexp_build (r_sig, NULL, "(sig-val(eddsa(r%M)(s%M)))", sig_r, sig_s); } else if ((ctx.flags & PUBKEY_FLAG_GOST)) { rc = _gcry_ecc_gost_sign (data, ec, sig_r, sig_s); if (!rc) rc = sexp_build (r_sig, NULL, "(sig-val(gost(r%M)(s%M)))", sig_r, sig_s); } else if ((ctx.flags & PUBKEY_FLAG_SM2)) { rc = _gcry_ecc_sm2_sign (data, ec, sig_r, sig_s, ctx.flags, ctx.hash_algo); if (!rc) rc = sexp_build (r_sig, NULL, "(sig-val(sm2(r%M)(s%M)))", sig_r, sig_s); } else { rc = _gcry_ecc_ecdsa_sign (data, ec, sig_r, sig_s, ctx.flags, ctx.hash_algo); if (!rc) rc = sexp_build (r_sig, NULL, "(sig-val(ecdsa(r%M)(s%M)))", sig_r, sig_s); } leave: _gcry_mpi_release (sig_r); _gcry_mpi_release (sig_s); _gcry_mpi_release (data); _gcry_mpi_ec_free (ec); _gcry_pk_util_free_encoding_ctx (&ctx); if (DBG_CIPHER) log_debug ("ecc_sign => %s\n", gpg_strerror (rc)); return rc; } static gcry_err_code_t ecc_verify (gcry_sexp_t s_sig, gcry_sexp_t s_data, gcry_sexp_t s_keyparms) { gcry_err_code_t rc; struct pk_encoding_ctx ctx; gcry_sexp_t l1 = NULL; gcry_mpi_t sig_r = NULL; gcry_mpi_t sig_s = NULL; gcry_mpi_t data = NULL; int sigflags; mpi_ec_t ec = NULL; int flags = 0; _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_VERIFY, ecc_get_nbits (s_keyparms)); /* * Extract the key. */ rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_verify", s_keyparms, NULL); if (rc) goto leave; if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n || !ec->Q) { rc = GPG_ERR_NO_OBJ; goto leave; } if (ec->model == MPI_EC_MONTGOMERY) { if (DBG_CIPHER) log_debug ("ecc_verify: Can't use a Montgomery curve\n"); rc = GPG_ERR_INTERNAL; goto leave; } ctx.flags |= flags; if (ec->model == MPI_EC_EDWARDS && ec->dialect == ECC_DIALECT_SAFECURVE) ctx.flags |= PUBKEY_FLAG_EDDSA; /* Clear hash algo for EdDSA. */ if ((ctx.flags & PUBKEY_FLAG_EDDSA)) ctx.hash_algo = GCRY_MD_NONE; /* Extract the data. */ rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx); if (rc) goto leave; if (DBG_CIPHER) log_mpidump ("ecc_verify data", data); /* Hash algo is determined by curve in EdDSA. Fill it if not specified. */ if ((ctx.flags & PUBKEY_FLAG_EDDSA) && !ctx.hash_algo) { if (ec->dialect == ECC_DIALECT_ED25519) ctx.hash_algo = GCRY_MD_SHA512; else if (ec->dialect == ECC_DIALECT_SAFECURVE) ctx.hash_algo = GCRY_MD_SHAKE256; } /* * Extract the signature value. */ rc = _gcry_pk_util_preparse_sigval (s_sig, ecc_names, &l1, &sigflags); if (rc) goto leave; rc = sexp_extract_param (l1, NULL, (sigflags & PUBKEY_FLAG_EDDSA)? "/rs":"rs", &sig_r, &sig_s, NULL); if (rc) goto leave; if (DBG_CIPHER) { log_mpidump ("ecc_verify s_r", sig_r); log_mpidump ("ecc_verify s_s", sig_s); } if ((ctx.flags & PUBKEY_FLAG_EDDSA) ^ (sigflags & PUBKEY_FLAG_EDDSA)) { rc = GPG_ERR_CONFLICT; /* Inconsistent use of flag/algoname. */ goto leave; } /* * Verify the signature. */ if ((sigflags & PUBKEY_FLAG_EDDSA)) { rc = _gcry_ecc_eddsa_verify (data, ec, sig_r, sig_s, &ctx); } else if ((sigflags & PUBKEY_FLAG_GOST)) { rc = _gcry_ecc_gost_verify (data, ec, sig_r, sig_s); } else if ((sigflags & PUBKEY_FLAG_SM2)) { rc = _gcry_ecc_sm2_verify (data, ec, sig_r, sig_s); } else { rc = _gcry_ecc_ecdsa_verify (data, ec, sig_r, sig_s); } leave: _gcry_mpi_release (data); _gcry_mpi_release (sig_r); _gcry_mpi_release (sig_s); _gcry_mpi_ec_free (ec); sexp_release (l1); _gcry_pk_util_free_encoding_ctx (&ctx); if (DBG_CIPHER) log_debug ("ecc_verify => %s\n", rc?gpg_strerror (rc):"Good"); return rc; } /* ecdh raw is classic 2-round DH protocol published in 1976. * * Overview of ecc_encrypt_raw and ecc_decrypt_raw. * * As with any PK operation, encrypt version uses a public key and * decrypt -- private. * * Symbols used below: * G - field generator point * d - private long-term scalar * dG - public long-term key * k - ephemeral scalar * kG - ephemeral public key * dkG - shared secret * * ecc_encrypt_raw description: * input: * data[0] : private scalar (k) * output: A new S-expression with the parameters: * s : shared point (kdG) * e : generated ephemeral public key (kG) * * ecc_decrypt_raw description: * input: * data[0] : a point kG (ephemeral public key) * output: * result[0] : shared point (kdG) */ static gcry_err_code_t ecc_encrypt_raw (gcry_sexp_t *r_ciph, gcry_sexp_t s_data, gcry_sexp_t keyparms) { unsigned int nbits; gcry_err_code_t rc; struct pk_encoding_ctx ctx; gcry_mpi_t mpi_s = NULL; gcry_mpi_t mpi_e = NULL; gcry_mpi_t data = NULL; mpi_ec_t ec = NULL; int flags = 0; int no_error_on_infinity; _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_ENCRYPT, (nbits = ecc_get_nbits (keyparms))); /* * Extract the key. */ rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_encrypt", keyparms, NULL); if (rc) goto leave; if (ec->dialect == ECC_DIALECT_SAFECURVE) { ctx.flags |= PUBKEY_FLAG_RAW_FLAG; no_error_on_infinity = 1; } else if ((flags & PUBKEY_FLAG_DJB_TWEAK)) no_error_on_infinity = 1; else no_error_on_infinity = 0; /* * Extract the data. */ rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx); if (rc) goto leave; /* * Tweak the scalar bits by cofactor and number of bits of the field. * It assumes the cofactor is a power of 2. */ if ((flags & PUBKEY_FLAG_DJB_TWEAK)) { int i; for (i = 0; (ec->h & (1 << i)) == 0; i++) mpi_clear_bit (data, i); mpi_set_highbit (data, ec->nbits - 1); } if (DBG_CIPHER) log_mpidump ("ecc_encrypt data", data); if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n || !ec->Q) { rc = GPG_ERR_NO_OBJ; goto leave; } if ((ctx.flags & PUBKEY_FLAG_SM2)) { /* All encryption will be done, return it. */ rc = _gcry_ecc_sm2_encrypt (r_ciph, data, ec); goto leave; } /* The following is false: assert( mpi_cmp_ui( R.x, 1 )==0 );, so */ { mpi_point_struct R; /* Result that we return. */ gcry_mpi_t x, y; unsigned char *rawmpi; unsigned int rawmpilen; rc = 0; x = mpi_new (0); if (ec->model == MPI_EC_MONTGOMERY) y = NULL; else y = mpi_new (0); point_init (&R); /* R = kQ <=> R = kdG */ _gcry_mpi_ec_mul_point (&R, data, ec->Q, ec); if (_gcry_mpi_ec_get_affine (x, y, &R, ec)) { /* * Here, X is 0. In the X25519 computation on Curve25519, X0 * function maps infinity to zero. So, when PUBKEY_FLAG_DJB_TWEAK * is enabled, return the result of 0 not raising an error. * * This is a corner case. It never occurs with properly * generated public keys, but it might happen with blindly * imported public key which might not follow the key * generation procedure. */ if (!no_error_on_infinity) { /* It's not for X25519, then, the input data was simply wrong. */ rc = GPG_ERR_INV_DATA; goto leave_main; } } if (y) mpi_s = _gcry_ecc_ec2os (x, y, ec->p); else { rc = _gcry_ecc_mont_encodepoint (x, nbits, ec->dialect != ECC_DIALECT_SAFECURVE, &rawmpi, &rawmpilen); if (rc) goto leave_main; mpi_s = mpi_new (0); mpi_set_opaque (mpi_s, rawmpi, rawmpilen*8); } /* R = kG */ _gcry_mpi_ec_mul_point (&R, data, ec->G, ec); if (_gcry_mpi_ec_get_affine (x, y, &R, ec)) { rc = GPG_ERR_INV_DATA; goto leave_main; } if (y) mpi_e = _gcry_ecc_ec2os (x, y, ec->p); else { rc = _gcry_ecc_mont_encodepoint (x, nbits, ec->dialect != ECC_DIALECT_SAFECURVE, &rawmpi, &rawmpilen); if (!rc) { mpi_e = mpi_new (0); mpi_set_opaque (mpi_e, rawmpi, rawmpilen*8); } } leave_main: mpi_free (x); mpi_free (y); point_free (&R); if (rc) goto leave; } if (!rc) rc = sexp_build (r_ciph, NULL, "(enc-val(ecdh(s%m)(e%m)))", mpi_s, mpi_e); leave: _gcry_mpi_release (data); _gcry_mpi_release (mpi_s); _gcry_mpi_release (mpi_e); _gcry_mpi_ec_free (ec); _gcry_pk_util_free_encoding_ctx (&ctx); if (DBG_CIPHER) log_debug ("ecc_encrypt => %s\n", gpg_strerror (rc)); return rc; } /* input: * data[0] : a point kG (ephemeral public key) * output: * resaddr[0] : shared point kdG * * see ecc_encrypt_raw for details. */ static gcry_err_code_t ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms) { unsigned int nbits; gpg_err_code_t rc; struct pk_encoding_ctx ctx; gcry_sexp_t l1 = NULL; gcry_mpi_t data_e = NULL; mpi_ec_t ec = NULL; mpi_point_struct kG; mpi_point_struct R; gcry_mpi_t r = NULL; int flags = 0; int enable_specific_point_validation; point_init (&kG); point_init (&R); _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, (nbits = ecc_get_nbits (keyparms))); /* * Extract the key. */ rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_decrypt", keyparms, NULL); if (rc) goto leave; if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n || !ec->d) { rc = GPG_ERR_NO_OBJ; goto leave; } /* * Extract the data. */ rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx); if (rc) goto leave; if ((ctx.flags & PUBKEY_FLAG_SM2)) { /* All decryption will be done, return it. */ rc = _gcry_ecc_sm2_decrypt (r_plain, l1, ec); goto leave; } else { rc = sexp_extract_param (l1, NULL, "/e", &data_e, NULL); if (rc) goto leave; if (DBG_CIPHER) log_printmpi ("ecc_decrypt d_e", data_e); } if (ec->dialect == ECC_DIALECT_SAFECURVE || (flags & PUBKEY_FLAG_DJB_TWEAK)) enable_specific_point_validation = 1; else enable_specific_point_validation = 0; /* * Compute the plaintext. */ if (ec->model == MPI_EC_MONTGOMERY) rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG); else rc = _gcry_ecc_sec_decodepoint (data_e, ec, &kG); if (rc) goto leave; if (DBG_CIPHER) log_printpnt ("ecc_decrypt kG", &kG, NULL); if (enable_specific_point_validation) { /* For X25519, by its definition, validation should not be done. */ /* (Instead, we do output check.) * * However, to mitigate secret key leak from our implementation, * we also do input validation here. For constant-time * implementation, we can remove this input validation. */ if (_gcry_mpi_ec_bad_point (&kG, ec)) { rc = GPG_ERR_INV_DATA; goto leave; } } else if (!_gcry_mpi_ec_curve_point (&kG, ec)) { rc = GPG_ERR_INV_DATA; goto leave; } /* R = dkG */ _gcry_mpi_ec_mul_point (&R, ec->d, &kG, ec); /* The following is false: assert( mpi_cmp_ui( R.x, 1 )==0 );, so: */ { gcry_mpi_t x, y; x = mpi_new (0); if (ec->model == MPI_EC_MONTGOMERY) y = NULL; else y = mpi_new (0); if (_gcry_mpi_ec_get_affine (x, y, &R, ec)) { rc = GPG_ERR_INV_DATA; goto leave; /* * Note for X25519. * * By the definition of X25519, this is the case where X25519 * returns 0, mapping infinity to zero. However, we * deliberately let it return an error. * * For X25519 ECDH, comming here means that it might be * decrypted by anyone with the shared secret of 0 (the result * of this function could be always 0 by other scalar values, * other than the private key of D). * * So, it looks like an encrypted message but it can be * decrypted by anyone, or at least something wrong * happens. Recipient should not proceed as if it were * properly encrypted message. * * This handling is needed for our major usage of GnuPG, * where it does the One-Pass Diffie-Hellman method, * C(1, 1, ECC CDH), with an ephemeral key. */ } if (y) r = _gcry_ecc_ec2os (x, y, ec->p); else { unsigned char *rawmpi; unsigned int rawmpilen; rc = _gcry_ecc_mont_encodepoint (x, nbits, ec->dialect != ECC_DIALECT_SAFECURVE, &rawmpi, &rawmpilen); if (rc) goto leave; r = mpi_new (0); mpi_set_opaque (r, rawmpi, rawmpilen*8); } if (!r) rc = gpg_err_code_from_syserror (); else rc = 0; mpi_free (x); mpi_free (y); } if (DBG_CIPHER) log_printmpi ("ecc_decrypt res", r); if (!rc) rc = sexp_build (r_plain, NULL, "(value %m)", r); leave: point_free (&R); point_free (&kG); _gcry_mpi_release (r); _gcry_mpi_release (data_e); sexp_release (l1); _gcry_mpi_ec_free (ec); _gcry_pk_util_free_encoding_ctx (&ctx); if (DBG_CIPHER) log_debug ("ecc_decrypt => %s\n", gpg_strerror (rc)); return rc; } /* Return the number of bits for the key described by PARMS. On error * 0 is returned. The format of PARMS starts with the algorithm name; * for example: * * (ecc * (curve ) * (p ) * (a ) * (b ) * (g ) * (n ) * (q )) * * More parameters may be given. Either P or CURVE is needed. */ static unsigned int ecc_get_nbits (gcry_sexp_t parms) { gcry_sexp_t l1; gcry_mpi_t p; unsigned int nbits = 0; char *curve; l1 = sexp_find_token (parms, "p", 1); if (!l1) { /* Parameter P not found - check whether we have "curve". */ l1 = sexp_find_token (parms, "curve", 5); if (!l1) return 0; /* Neither P nor CURVE found. */ curve = sexp_nth_string (l1, 1); sexp_release (l1); if (!curve) return 0; /* No curve name given (or out of core). */ if (_gcry_ecc_fill_in_curve (0, curve, NULL, &nbits)) nbits = 0; xfree (curve); } else { p = sexp_nth_mpi (l1, 1, GCRYMPI_FMT_USG); sexp_release (l1); if (p) { nbits = mpi_get_nbits (p); _gcry_mpi_release (p); } } return nbits; } /* See rsa.c for a description of this function. */ static gpg_err_code_t compute_keygrip (gcry_md_hd_t md, gcry_sexp_t keyparms) { #define N_COMPONENTS 6 static const char names[N_COMPONENTS] = "pabgnq"; gpg_err_code_t rc; gcry_sexp_t l1; gcry_mpi_t values[N_COMPONENTS]; int idx; char *curvename = NULL; int flags = 0; enum gcry_mpi_ec_models model = 0; enum ecc_dialects dialect = 0; const unsigned char *raw; unsigned int n; + int maybe_uncompress; /* Clear the values first. */ for (idx=0; idx < N_COMPONENTS; idx++) values[idx] = NULL; /* Look for flags. */ l1 = sexp_find_token (keyparms, "flags", 0); if (l1) { rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL); if (rc) goto leave; } /* Extract the parameters. */ if ((flags & PUBKEY_FLAG_PARAM)) rc = sexp_extract_param (keyparms, NULL, "p?a?b?g?n?/q", &values[0], &values[1], &values[2], &values[3], &values[4], &values[5], NULL); else rc = sexp_extract_param (keyparms, NULL, "/q", &values[5], NULL); if (rc) goto leave; /* Check whether a curve parameter is available and use that to fill in missing values. */ sexp_release (l1); l1 = sexp_find_token (keyparms, "curve", 5); if (l1) { curvename = sexp_nth_string (l1, 1); if (curvename) { rc = _gcry_ecc_update_curve_param (curvename, &model, &dialect, &values[0], &values[1], &values[2], &values[3], &values[4]); if (rc) goto leave; } } /* Guess required fields if a curve parameter has not been given. FIXME: This is a crude hacks. We need to fix that. */ if (!curvename) { model = ((flags & PUBKEY_FLAG_EDDSA) ? MPI_EC_EDWARDS : MPI_EC_WEIERSTRASS); dialect = ((flags & PUBKEY_FLAG_EDDSA) ? ECC_DIALECT_ED25519 : ECC_DIALECT_STANDARD); } /* Check that all parameters are known and normalize all MPIs (that should not be required but we use an internal function later and thus we better make 100% sure that they are normalized). */ for (idx = 0; idx < N_COMPONENTS; idx++) if (!values[idx]) { rc = GPG_ERR_NO_OBJ; goto leave; } else _gcry_mpi_normalize (values[idx]); /* Uncompress the public key with the exception of EdDSA where compression is the default and we thus compute the keygrip using the compressed version. Because we don't support any non-eddsa compression, the only thing we need to do is to compress EdDSA. */ if ((flags & PUBKEY_FLAG_EDDSA) && dialect == ECC_DIALECT_ED25519) { const unsigned int pbits = mpi_get_nbits (values[0]); rc = _gcry_ecc_eddsa_ensure_compact (values[5], pbits); if (rc) goto leave; + maybe_uncompress = 0; } else if ((flags & PUBKEY_FLAG_DJB_TWEAK)) { /* Remove the prefix 0x40 for keygrip computation. */ raw = mpi_get_opaque (values[5], &n); if (raw) { n = (n + 7)/8; if (n > 1 && (n%2) && raw[0] == 0x40) if (!_gcry_mpi_set_opaque_copy (values[5], raw + 1, (n - 1)*8)) rc = gpg_err_code_from_syserror (); } else { rc = GPG_ERR_INV_OBJ; goto leave; } + maybe_uncompress = 0; } + else + maybe_uncompress = 1; /* Hash them all. */ for (idx = 0; idx < N_COMPONENTS; idx++) { char buf[30]; + unsigned char *rawbuffer; + unsigned int rawlen; if (mpi_is_opaque (values[idx])) { - raw = mpi_get_opaque (values[idx], &n); - n = (n + 7)/8; - snprintf (buf, sizeof buf, "(1:%c%u:", names[idx], n); - _gcry_md_write (md, buf, strlen (buf)); - _gcry_md_write (md, raw, n); - _gcry_md_write (md, ")", 1); + rawbuffer = NULL; + raw = mpi_get_opaque (values[idx], &rawlen); + rawlen = (rawlen + 7)/8; } else { - unsigned char *rawmpi; - unsigned int rawmpilen; - - rawmpi = _gcry_mpi_get_buffer (values[idx], 0, &rawmpilen, NULL); - if (!rawmpi) + rawbuffer = _gcry_mpi_get_buffer (values[idx], 0, &rawlen, NULL); + if (!rawbuffer) { rc = gpg_err_code_from_syserror (); goto leave; } - snprintf (buf, sizeof buf, "(1:%c%u:", names[idx], rawmpilen); - _gcry_md_write (md, buf, strlen (buf)); - _gcry_md_write (md, rawmpi, rawmpilen); - _gcry_md_write (md, ")", 1); - xfree (rawmpi); + raw = rawbuffer; + } + + if (maybe_uncompress && idx == 5 && rawlen > 1 + && (*raw == 0x02 || *raw == 0x03)) + { + /* This is a compressed Q - uncompress. */ + mpi_ec_t ec = NULL; + gcry_mpi_t x, y; + gcry_mpi_t x3; + gcry_mpi_t t; + gcry_mpi_t p1_4; + int y_bit = (*raw == 0x03); + + /* We need to get the curve parameters as MPIs so that we + * can do computations. We have them in VALUES but it is + * possible that the caller provided them as opaque MPIs. */ + rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_keygrip", + keyparms, NULL); + if (rc) + goto leave; + if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n) + { + rc = GPG_ERR_NO_OBJ; + _gcry_mpi_ec_free (ec); + goto leave; + } + + if (!mpi_test_bit (ec->p, 1)) + { + /* No support for point compression for this curve. */ + rc = GPG_ERR_NOT_IMPLEMENTED; + _gcry_mpi_ec_free (ec); + xfree (rawbuffer); + goto leave; + } + + raw++; + rawlen--; + rc = _gcry_mpi_scan (&x, GCRYMPI_FMT_USG, raw, rawlen, NULL); + if (rc) + { + _gcry_mpi_ec_free (ec); + xfree (rawbuffer); + goto leave; + } + + /* + * Recover Y. The Weierstrass curve: y^2 = x^3 + a*x + b + */ + + x3 = mpi_new (0); + t = mpi_new (0); + p1_4 = mpi_new (0); + y = mpi_new (0); + + /* Compute right hand side. */ + mpi_powm (x3, x, mpi_const (MPI_C_THREE), ec->p); + mpi_mul (t, ec->a, x); + mpi_mod (t, t, ec->p); + mpi_add (t, t, ec->b); + mpi_mod (t, t, ec->p); + mpi_add (t, t, x3); + mpi_mod (t, t, ec->p); + + /* + * When p mod 4 = 3, modular square root of A can be computed by + * A^((p+1)/4) mod p + */ + + /* Compute (p+1)/4 into p1_4 */ + mpi_rshift (p1_4, ec->p, 2); + _gcry_mpi_add_ui (p1_4, p1_4, 1); + + mpi_powm (y, t, p1_4, ec->p); + + if (y_bit != mpi_test_bit (y, 0)) + mpi_sub (y, ec->p, y); + + mpi_free (p1_4); + mpi_free (t); + mpi_free (x3); + + xfree (rawbuffer); + rawbuffer = _gcry_ecc_ec2os_buf (x, y, ec->p, &rawlen); + raw = rawbuffer; + + mpi_free (x); + mpi_free (y); + _gcry_mpi_ec_free (ec); } + + snprintf (buf, sizeof buf, "(1:%c%u:", names[idx], rawlen); + _gcry_md_write (md, buf, strlen (buf)); + _gcry_md_write (md, raw, rawlen); + _gcry_md_write (md, ")", 1); + xfree (rawbuffer); } leave: xfree (curvename); sexp_release (l1); for (idx = 0; idx < N_COMPONENTS; idx++) _gcry_mpi_release (values[idx]); return rc; #undef N_COMPONENTS } /* Low-level API helper functions. */ /* This is the worker function for gcry_pubkey_get_sexp for ECC algorithms. Note that the caller has already stored NULL at R_SEXP. */ gpg_err_code_t _gcry_pk_ecc_get_sexp (gcry_sexp_t *r_sexp, int mode, mpi_ec_t ec) { gpg_err_code_t rc; gcry_mpi_t mpi_G = NULL; gcry_mpi_t mpi_Q = NULL; if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n) return GPG_ERR_BAD_CRYPT_CTX; if (mode == GCRY_PK_GET_SECKEY && !ec->d) return GPG_ERR_NO_SECKEY; /* Compute the public point if it is missing. */ if (!ec->Q && ec->d) ec->Q = _gcry_ecc_compute_public (NULL, ec); /* Encode G and Q. */ mpi_G = _gcry_mpi_ec_ec2os (ec->G, ec); if (!mpi_G) { rc = GPG_ERR_BROKEN_PUBKEY; goto leave; } if (!ec->Q) { rc = GPG_ERR_BAD_CRYPT_CTX; goto leave; } if (ec->dialect == ECC_DIALECT_ED25519) { unsigned char *encpk; unsigned int encpklen; rc = _gcry_ecc_eddsa_encodepoint (ec->Q, ec, NULL, NULL, 0, &encpk, &encpklen); if (rc) goto leave; mpi_Q = mpi_set_opaque (NULL, encpk, encpklen*8); encpk = NULL; } else if (ec->model == MPI_EC_MONTGOMERY) { unsigned char *encpk; unsigned int encpklen; rc = _gcry_ecc_mont_encodepoint (ec->Q->x, ec->nbits, ec->dialect != ECC_DIALECT_SAFECURVE, &encpk, &encpklen); if (rc) goto leave; mpi_Q = mpi_set_opaque (NULL, encpk, encpklen*8); } else { mpi_Q = _gcry_mpi_ec_ec2os (ec->Q, ec); } if (!mpi_Q) { rc = GPG_ERR_BROKEN_PUBKEY; goto leave; } /* Fixme: We should return a curve name instead of the parameters if if know that they match a curve. */ if (ec->d && (!mode || mode == GCRY_PK_GET_SECKEY)) { /* Let's return a private key. */ rc = sexp_build (r_sexp, NULL, "(private-key(ecc(p%m)(a%m)(b%m)(g%m)(n%m)(h%u)(q%m)(d%m)))", ec->p, ec->a, ec->b, mpi_G, ec->n, ec->h, mpi_Q, ec->d); } else if (ec->Q) { /* Let's return a public key. */ rc = sexp_build (r_sexp, NULL, "(public-key(ecc(p%m)(a%m)(b%m)(g%m)(n%m)(h%u)(q%m)))", ec->p, ec->a, ec->b, mpi_G, ec->n, ec->h, mpi_Q); } else rc = GPG_ERR_BAD_CRYPT_CTX; leave: mpi_free (mpi_Q); mpi_free (mpi_G); return rc; } /* Self-test section. */ static const char * selftest_sign (gcry_sexp_t pkey, gcry_sexp_t skey) { /* Sample data from RFC 6979 section A.2.5, hash is of message "sample" */ static const char sample_data[] = "(data (flags rfc6979)" " (hash sha256 #af2bdbe1aa9b6ec1e2ade1d694f41fc71a831d0268e98915" /**/ "62113d8a62add1bf#))"; static const char sample_data_bad[] = "(data (flags rfc6979)" " (hash sha256 #bf2bdbe1aa9b6ec1e2ade1d694f41fc71a831d0268e98915" /**/ "62113d8a62add1bf#))"; static const char signature_r[] = "efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716"; static const char signature_s[] = "f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8"; const char *errtxt = NULL; gcry_error_t err; gcry_sexp_t data = NULL; gcry_sexp_t data_bad = NULL; gcry_sexp_t sig = NULL; gcry_sexp_t l1 = NULL; gcry_sexp_t l2 = NULL; gcry_mpi_t r = NULL; gcry_mpi_t s = NULL; gcry_mpi_t calculated_r = NULL; gcry_mpi_t calculated_s = NULL; int cmp; err = sexp_sscan (&data, NULL, sample_data, strlen (sample_data)); if (!err) err = sexp_sscan (&data_bad, NULL, sample_data_bad, strlen (sample_data_bad)); if (!err) err = _gcry_mpi_scan (&r, GCRYMPI_FMT_HEX, signature_r, 0, NULL); if (!err) err = _gcry_mpi_scan (&s, GCRYMPI_FMT_HEX, signature_s, 0, NULL); if (err) { errtxt = "converting data failed"; goto leave; } err = _gcry_pk_sign (&sig, data, skey); if (err) { errtxt = "signing failed"; goto leave; } /* check against known signature */ errtxt = "signature validity failed"; l1 = _gcry_sexp_find_token (sig, "sig-val", 0); if (!l1) goto leave; l2 = _gcry_sexp_find_token (l1, "ecdsa", 0); if (!l2) goto leave; sexp_release (l1); l1 = l2; l2 = _gcry_sexp_find_token (l1, "r", 0); if (!l2) goto leave; calculated_r = _gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG); if (!calculated_r) goto leave; sexp_release (l2); l2 = _gcry_sexp_find_token (l1, "s", 0); if (!l2) goto leave; calculated_s = _gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG); if (!calculated_s) goto leave; errtxt = "known sig check failed"; cmp = _gcry_mpi_cmp (r, calculated_r); if (cmp) goto leave; cmp = _gcry_mpi_cmp (s, calculated_s); if (cmp) goto leave; errtxt = NULL; /* verify generated signature */ err = _gcry_pk_verify (sig, data, pkey); if (err) { errtxt = "verify failed"; goto leave; } err = _gcry_pk_verify (sig, data_bad, pkey); if (gcry_err_code (err) != GPG_ERR_BAD_SIGNATURE) { errtxt = "bad signature not detected"; goto leave; } leave: sexp_release (sig); sexp_release (data_bad); sexp_release (data); sexp_release (l1); sexp_release (l2); mpi_release (r); mpi_release (s); mpi_release (calculated_r); mpi_release (calculated_s); return errtxt; } static gpg_err_code_t selftests_ecdsa (selftest_report_func_t report) { const char *what; const char *errtxt; gcry_error_t err; gcry_sexp_t skey = NULL; gcry_sexp_t pkey = NULL; what = "convert"; err = sexp_sscan (&skey, NULL, sample_secret_key_secp256, strlen (sample_secret_key_secp256)); if (!err) err = sexp_sscan (&pkey, NULL, sample_public_key_secp256, strlen (sample_public_key_secp256)); if (err) { errtxt = _gcry_strerror (err); goto failed; } what = "key consistency"; err = ecc_check_secret_key(skey); if (err) { errtxt = _gcry_strerror (err); goto failed; } what = "sign"; errtxt = selftest_sign (pkey, skey); if (errtxt) goto failed; sexp_release(pkey); sexp_release(skey); return 0; /* Succeeded. */ failed: sexp_release(pkey); sexp_release(skey); if (report) report ("pubkey", GCRY_PK_ECC, what, errtxt); return GPG_ERR_SELFTEST_FAILED; } /* Run a full self-test for ALGO and return 0 on success. */ static gpg_err_code_t run_selftests (int algo, int extended, selftest_report_func_t report) { (void)extended; if (algo != GCRY_PK_ECC) return GPG_ERR_PUBKEY_ALGO; return selftests_ecdsa (report); } gcry_pk_spec_t _gcry_pubkey_spec_ecc = { GCRY_PK_ECC, { 0, 1 }, (GCRY_PK_USAGE_SIGN | GCRY_PK_USAGE_ENCR), "ECC", ecc_names, "pabgnhq", "pabgnhqd", "se", "rs", "pabgnhq", ecc_generate, ecc_check_secret_key, ecc_encrypt_raw, ecc_decrypt_raw, ecc_sign, ecc_verify, ecc_get_nbits, run_selftests, compute_keygrip, _gcry_ecc_get_curve, _gcry_ecc_get_param_sexp }; diff --git a/tests/keygrip.c b/tests/keygrip.c index 56fbba80..cfccc06e 100644 --- a/tests/keygrip.c +++ b/tests/keygrip.c @@ -1,341 +1,385 @@ /* keygrip.c - verifies that keygrips are calculated as expected * Copyright (C) 2005 Free Software Foundation, Inc. * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #define PGM "keygrip" #include "t-common.h" static int repetitions; static void print_hex (const char *text, const void *buf, size_t n) { const unsigned char *p = buf; fputs (text, stdout); for (; n; n--, p++) printf ("%02X", *p); putchar ('\n'); } static struct { int algo; const char *key; const unsigned char grip[20]; } key_grips[] = { { GCRY_PK_RSA, "(private-key" " (rsa" " (n #00B6B509596A9ECABC939212F891E656A626BA07DA8521A9CAD4C08E640C04052FBB87F424EF1A0275A48A9299AC9DB69ABE3D0124E6C756B1F7DFB9B842D6251AEA6EE85390495CADA73D671537FCE5850A932F32BAB60AB1AC1F852C1F83C625E7A7D70CDA9EF16D5C8E47739D77DF59261ABE8454807FF441E143FBD37F8545#)" " (e #010001#)" " (d #077AD3DE284245F4806A1B82B79E616FBDE821C82D691A65665E57B5FAD3F34E67F401E7BD2E28699E89D9C496CF821945AE83AC7A1231176A196BA6027E77D85789055D50404A7A2A95B1512F91F190BBAEF730ED550D227D512F89C0CDB31AC06FA9A19503DDF6B66D0B42B9691BFD6140EC1720FFC48AE00C34796DC899E5#)" " (p #00D586C78E5F1B4BF2E7CD7A04CA091911706F19788B93E44EE20AAF462E8363E98A72253ED845CCBF2481BB351E8557C85BCFFF0DABDBFF8E26A79A0938096F27#)" " (q #00DB0CDF60F26F2A296C88D6BF9F8E5BE45C0DDD713C96CC73EBCB48B061740943F21D2A93D6E42A7211E7F02A95DCED6C390A67AD21ECF739AE8A0CA46FF2EBB3#)" " (u #33149195F16912DB20A48D020DBC3B9E3881B39D722BF79378F6340F43148A6E9FC5F53E2853B7387BA4443BA53A52FCA8173DE6E85B42F9783D4A7817D0680B#)))", "\x32\xCF\xFA\x85\xB1\x79\x1F\xBB\x26\x14\xE9\x1A\xFD\xF3\xAF\xE3\x32\x08\x2E\x25" }, { GCRY_PK_DSA, " (public-key" " (dsa" " (p #0084E4C626E16005770BD9509ABF7354492E85B8C0060EFAAAEC617F725B592FAA59DF5460575F41022776A9718CE62EDD542AB73C7720869EBDBC834D174ADCD7136827DF51E2613545A25CA573BC502A61B809000B6E35F5EB7FD6F18C35678C23EA1C3638FB9CFDBA2800EE1B62F41A4479DE824F2834666FBF8DC5B53C2617#)" " (q #00B0E6F710051002A9F425D98A677B18E0E5B038AB#)" " (g #44370CEE0FE8609994183DBFEBA7EEA97D466838BCF65EFF506E35616DA93FA4E572A2F08886B74977BC00CA8CD3DBEA7AEB7DB8CBB180E6975E0D2CA76E023E6DE9F8CCD8826EBA2F72B8516532F6001DEFFAE76AA5E59E0FA33DBA3999B4E92D1703098CDEDCC416CF008801964084CDE1980132B2B78CB4CE9C15A559528B#)" " (y #3D5DD14AFA2BF24A791E285B90232213D0E3BA74AB1109E768AED19639A322F84BB7D959E2BA92EF73DE4C7F381AA9F4053CFA3CD4527EF9043E304E5B95ED0A3A5A9D590AA641C13DB2B6E32B9B964A6A2C730DD3EA7C8E13F7A140AFF1A91CE375E9B9B960384779DC4EA180FA1F827C52288F366C0770A220F50D6D8FD6F6#)))", "\x04\xA3\x4F\xA0\x2B\x03\x94\xD7\x32\xAD\xD5\x9B\x50\xAF\xDB\x5D\x57\x22\xA6\x10" }, { GCRY_PK_DSA, "(private-key" " (dsa" " (p #0084E4C626E16005770BD9509ABF7354492E85B8C0060EFAAAEC617F725B592FAA59DF5460575F41022776A9718CE62EDD542AB73C7720869EBDBC834D174ADCD7136827DF51E2613545A25CA573BC502A61B809000B6E35F5EB7FD6F18C35678C23EA1C3638FB9CFDBA2800EE1B62F41A4479DE824F2834666FBF8DC5B53C2617#)" " (q #00B0E6F710051002A9F425D98A677B18E0E5B038AB#)" " (g #44370CEE0FE8609994183DBFEBA7EEA97D466838BCF65EFF506E35616DA93FA4E572A2F08886B74977BC00CA8CD3DBEA7AEB7DB8CBB180E6975E0D2CA76E023E6DE9F8CCD8826EBA2F72B8516532F6001DEFFAE76AA5E59E0FA33DBA3999B4E92D1703098CDEDCC416CF008801964084CDE1980132B2B78CB4CE9C15A559528B#)" " (y #3D5DD14AFA2BF24A791E285B90232213D0E3BA74AB1109E768AED19639A322F84BB7D959E2BA92EF73DE4C7F381AA9F4053CFA3CD4527EF9043E304E5B95ED0A3A5A9D590AA641C13DB2B6E32B9B964A6A2C730DD3EA7C8E13F7A140AFF1A91CE375E9B9B960384779DC4EA180FA1F827C52288F366C0770A220F50D6D8FD6F6#)" " (x #0087F9E91BFBCC1163DE71ED86D557708E32F8ADDE#)))", "\x04\xA3\x4F\xA0\x2B\x03\x94\xD7\x32\xAD\xD5\x9B\x50\xAF\xDB\x5D\x57\x22\xA6\x10" }, { GCRY_PK_ECDSA, "(public-key" " (ecdsa(flags param)" " (p #00FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF#)" " (a #00FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC#)" " (b #5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B#)" " (g #046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5#)" " (n #00FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551#)" " (h #000000000000000000000000000000000000000000000000000000000000000001#)" " (q #04C8A4CEC2E9A9BC8E173531A67B0840DF345C32E261ADD780E6D83D56EFADFD5DE872F8B854819B59543CE0B7F822330464FBC4E6324DADDCD9D059554F63B344#)))", "\xE6\xDF\x94\x2D\xBD\x8C\x77\x05\xA3\xDD\x41\x6E\xFC\x04\x01\xDB\x31\x0E\x99\xB6" }, { GCRY_PK_ECDSA, "(public-key" " (ecdsa(flags param)" " (p #00FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF#)" " (curve \"NIST P-256\")" " (b #5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B#)" " (g #046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5#)" " (n #00FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551#)" " (h #000000000000000000000000000000000000000000000000000000000000000001#)" " (q #04C8A4CEC2E9A9BC8E173531A67B0840DF345C32E261ADD780E6D83D56EFADFD5DE872F8B854819B59543CE0B7F822330464FBC4E6324DADDCD9D059554F63B344#)))", "\xE6\xDF\x94\x2D\xBD\x8C\x77\x05\xA3\xDD\x41\x6E\xFC\x04\x01\xDB\x31\x0E\x99\xB6" }, { GCRY_PK_ECDSA, "(public-key" " (ecdsa" " (p #00FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF#)" " (curve \"NIST P-256\")" " (b #5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B#)" " (g #046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5#)" " (n #00FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551#)" " (h #000000000000000000000000000000000000000000000000000000000000000001#)" " (q #04C8A4CEC2E9A9BC8E173531A67B0840DF345C32E261ADD780E6D83D56EFADFD5DE872F8B854819B59543CE0B7F822330464FBC4E6324DADDCD9D059554F63B344#)))", "\xE6\xDF\x94\x2D\xBD\x8C\x77\x05\xA3\xDD\x41\x6E\xFC\x04\x01\xDB\x31\x0E\x99\xB6" }, { GCRY_PK_ECDSA, "(public-key" " (ecdsa" " (curve secp256r1)" " (q #04C8A4CEC2E9A9BC8E173531A67B0840DF345C32E261ADD780E6D83D56EFADFD5DE872F8B854819B59543CE0B7F822330464FBC4E6324DADDCD9D059554F63B344#)))", "\xE6\xDF\x94\x2D\xBD\x8C\x77\x05\xA3\xDD\x41\x6E\xFC\x04\x01\xDB\x31\x0E\x99\xB6" }, { GCRY_PK_ECC, "(public-key" " (ecc" " (curve secp256r1)" " (q #04C8A4CEC2E9A9BC8E173531A67B0840DF345C32E261ADD780E6D83D56EFADFD5DE872F8B854819B59543CE0B7F822330464FBC4E6324DADDCD9D059554F63B344#)))", "\xE6\xDF\x94\x2D\xBD\x8C\x77\x05\xA3\xDD\x41\x6E\xFC\x04\x01\xDB\x31\x0E\x99\xB6" }, + { + GCRY_PK_ECC, + "(public-key" + " (ecc" + " (curve brainpoolP256r1)" + " (q #042ECD8679930BE2DB4AD42B8600BA3F80" + /* */"2D4D539BFF2F69B83EC9B7BBAA7F3406" + /* */"436DD11A1756AFE56CD93408410FCDA9" + /* */"BA95024EB613BD481A14FCFEC27A448A#)))", + "\x52\xBA\xD4\xB4\xA3\x2D\x32\xA1\xDD\x06" + "\x5E\x99\x0B\xF1\xAB\xC1\x13\x3D\x84\xD4" + }, + { /* Compressed form of above. */ + GCRY_PK_ECC, + "(public-key" + " (ecc" + " (curve brainpoolP256r1)" + " (q #022ECD8679930BE2DB4AD42B8600BA3F80" + /* */"2D4D539BFF2F69B83EC9B7BBAA7F3406#)))", + "\x52\xBA\xD4\xB4\xA3\x2D\x32\xA1\xDD\x06" + "\x5E\x99\x0B\xF1\xAB\xC1\x13\x3D\x84\xD4" + }, + { + GCRY_PK_ECC, + "(public-key" + " (ecc" + " (curve brainpoolP256r1)" + " (q #045B784CA008EE64AB3D85017EE0D2BE87" + /* */"558762C7300E0C8E06B1F9AF7C031458" + /* */"9EBBA41915313417BA54218EB0569C59" + /* */"0B156C76DBCAB6E84575E6EF68CE7B87#)))", + "\x99\x38\x6A\x82\x41\x96\x29\x9C\x89\x74" + "\xD6\xE1\xBF\x43\xAC\x9B\x9A\x12\xE7\x3F" + }, + { /* Compressed form of above. */ + GCRY_PK_ECC, + "(public-key" + " (ecc" + " (curve brainpoolP256r1)" + " (q #035B784CA008EE64AB3D85017EE0D2BE87" + /* */"558762C7300E0C8E06B1F9AF7C031458#)))", + "\x99\x38\x6A\x82\x41\x96\x29\x9C\x89\x74" + "\xD6\xE1\xBF\x43\xAC\x9B\x9A\x12\xE7\x3F" + }, { /* Ed25519 standard */ GCRY_PK_ECC, "(public-key" " (ecc" " (curve Ed25519)" " (q #04" " 1CC662926E7EFF4982B7FB8B928E61CD74CCDD85277CC57196C3AD20B611085F" " 47BD24842905C049257673B3F5249524E0A41FAA17B25B818D0F97E625F1A1D0#)" " ))", "\x0C\xCA\xB2\xFD\x48\x9A\x33\x40\x2C\xE8" "\xE0\x4A\x1F\xB2\x45\xEA\x80\x3D\x0A\xF1" }, { /* Ed25519+EdDSA */ GCRY_PK_ECC, "(public-key" " (ecc" " (curve Ed25519)(flags eddsa)" " (q #773E72848C1FD5F9652B29E2E7AF79571A04990E96F2016BF4E0EC1890C2B7DB#)" " ))", "\x9D\xB6\xC6\x4A\x38\x83\x0F\x49\x60\x70" "\x17\x89\x47\x55\x20\xBE\x8C\x82\x1F\x47" }, { /* Ed25519+EdDSA (with compression prefix) */ GCRY_PK_ECC, "(public-key" " (ecc" " (curve Ed25519)(flags eddsa)" " (q #40" " 773E72848C1FD5F9652B29E2E7AF79571A04990E96F2016BF4E0EC1890C2B7DB#)" " ))", "\x9D\xB6\xC6\x4A\x38\x83\x0F\x49\x60\x70" "\x17\x89\x47\x55\x20\xBE\x8C\x82\x1F\x47" }, { /* Ed25519+EdDSA (same but uncompressed)*/ GCRY_PK_ECC, "(public-key" " (ecc" " (curve Ed25519)(flags eddsa)" " (q #04" " 629ad237d1ed04dcd4abe1711dd699a1cf51b1584c4de7a4ef8b8a640180b26f" " 5bb7c29018ece0f46b01f2960e99041a5779afe7e2292b65f9d51f8c84723e77#)" " ))", "\x9D\xB6\xC6\x4A\x38\x83\x0F\x49\x60\x70" "\x17\x89\x47\x55\x20\xBE\x8C\x82\x1F\x47" }, { /* Cv25519 */ GCRY_PK_ECC, "(public-key" " (ecc" " (curve Curve25519)(flags djb-tweak)" " (q #40" " 918C1733127F6BF2646FAE3D081A18AE77111C903B906310B077505EFFF12740#)" " ))", "\x0F\x89\xA5\x65\xD3\xEA\x18\x7C\xE8\x39" "\x33\x23\x98\xF5\xD4\x80\x67\x7D\xF4\x9C" }, { /* Random key */ GCRY_PK_RSA, "(shadowed-private-key" " (rsa" " (n #00B493C79928398DA9D99AC0E949FE6EB62F683CB974FFFBFBC01066F5C9A89B" " D3DC48EAD7C65F36EA943C2B2C865C26C4884FF9EDFDA8C99C855B737D77EEF6" " B85DBC0CCEC0E900C1F89A6893A2A93E8B31028469B6927CEB2F08687E547C68" " 6B0A2F7E50A194FF7AB7637E03DE0912EF7F6E5F1EC37625BD1620CCC2E7A564" " 31E168CDAFBD1D9E61AE47A69A6FA03EF22F844528A710B2392F262B95A3078C" " F321DC8325F92A5691EF69F34FD0DE0B22C79D29DC87723FCADE463829E8E5F7" " D196D73D6C9C180F6A6A0DDBF7B9D8F7FA293C36163B12199EF6A1A95CAE4051" " E3069C522CC6C4A7110F663A5DAD20F66C13A1674D050088208FAE4F33B3AB51" " 03#)" " (e #00010001#)" " (shadowed t1-v1" " (#D2760001240102000005000123350000# OPENPGP.1)" ")))", "\xE5\x6E\xE6\xEE\x5A\x2F\xDC\x3E\x98\x9D" "\xFE\x49\xDA\xF5\x67\x43\xE3\x27\x28\x33" } }; static void check (void) { unsigned char buf[20]; unsigned char *ret; gcry_error_t err; gcry_sexp_t sexp; unsigned int i; int repn; for (i = 0; i < (sizeof (key_grips) / sizeof (*key_grips)); i++) { if (gcry_pk_test_algo (key_grips[i].algo)) { if (verbose) fprintf (stderr, "algo %d not available; test skipped\n", key_grips[i].algo); continue; } err = gcry_sexp_sscan (&sexp, NULL, key_grips[i].key, strlen (key_grips[i].key)); if (err) die ("scanning data %d failed: %s\n", i, gpg_strerror (err)); if (debug) info ("check(%d): s-exp='%s'\n", i, key_grips[i].key); for (repn=0; repn < repetitions; repn++) { ret = gcry_pk_get_keygrip (sexp, buf); if (!ret) die ("gcry_pk_get_keygrip failed for %d\n", i); if ( memcmp (key_grips[i].grip, buf, sizeof (buf)) ) { print_hex ("keygrip: ", buf, sizeof buf); die ("keygrip for %d does not match\n", i); } else if (debug && !repn) print_hex ("keygrip: ", buf, sizeof buf); } gcry_sexp_release (sexp); } } static void progress_handler (void *cb_data, const char *what, int printchar, int current, int total) { (void)cb_data; (void)what; (void)current; (void)total; putchar (printchar); } int main (int argc, char **argv) { int last_argc = -1; if (argc) { argc--; argv++; } while (argc && last_argc != argc ) { last_argc = argc; if (!strcmp (*argv, "--")) { argc--; argv++; break; } else if (!strcmp (*argv, "--verbose")) { verbose = 1; argc--; argv++; } else if (!strcmp (*argv, "--debug")) { verbose = 1; debug = 1; argc--; argv++; } else if (!strcmp (*argv, "--repetitions")) { argc--; argv++; if (argc) { repetitions = atoi(*argv); argc--; argv++; } } } if (repetitions < 1) repetitions = 1; if (!gcry_check_version (GCRYPT_VERSION)) die ("version mismatch\n"); gcry_set_progress_handler (progress_handler, NULL); xgcry_control ((GCRYCTL_DISABLE_SECMEM, 0)); xgcry_control ((GCRYCTL_INITIALIZATION_FINISHED, 0)); if (debug) xgcry_control ((GCRYCTL_SET_DEBUG_FLAGS, 1u, 0)); check (); return 0; }