diff --git a/cipher/ecc.c b/cipher/ecc.c index e25bf095..4e3e5b1a 100644 --- a/cipher/ecc.c +++ b/cipher/ecc.c @@ -1,2241 +1,2254 @@ /* 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", 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 (ECC_secret_key * sk, unsigned int nbits); static void test_ecdh_only_keys (ECC_secret_key * sk, 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. * @sk: A struct to receive the secret key. * @E: Parameters of the curve. * @ctx: Elliptic curve computation context. * @flags: Flags controlling aspects of the creation. * @nbits: Only for testing * @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 (ECC_secret_key *sk, elliptic_curve_t *E, mpi_ec_t ctx, int flags, unsigned int nbits, 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 = mpi_get_nbits (E->p); 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 (ctx->dialect == ECC_DIALECT_ED25519 || (flags & PUBKEY_FLAG_DJB_TWEAK)) { char *rndbuf; sk->d = mpi_snew (256); rndbuf = _gcry_random_bytes_secure (32, random_level); rndbuf[0] &= 0x7f; /* Clear bit 255. */ rndbuf[0] |= 0x40; /* Set bit 254. */ rndbuf[31] &= 0xf8; /* Clear bits 2..0 so that d mod 8 == 0 */ _gcry_mpi_set_buffer (sk->d, rndbuf, 32, 0); xfree (rndbuf); } else sk->d = _gcry_dsa_gen_k (E->n, random_level); /* Compute Q. */ _gcry_mpi_ec_mul_point (&Q, sk->d, &E->G, ctx); /* Copy the stuff to the key structures. */ sk->E.model = E->model; sk->E.dialect = E->dialect; sk->E.p = mpi_copy (E->p); sk->E.a = mpi_copy (E->a); sk->E.b = mpi_copy (E->b); point_init (&sk->E.G); point_set (&sk->E.G, &E->G); sk->E.n = mpi_copy (E->n); sk->E.h = mpi_copy (E->h); point_init (&sk->Q); x = mpi_new (pbits); if (r_y == NULL) y = NULL; else y = mpi_new (pbits); if (_gcry_mpi_ec_get_affine (x, y, &Q, ctx)) 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 || E->dialect == ECC_DIALECT_ED25519) point_set (&sk->Q, &Q); else { gcry_mpi_t negative; negative = mpi_new (pbits); if (E->model == MPI_EC_WEIERSTRASS) mpi_sub (negative, E->p, y); /* negative = p - y */ else mpi_sub (negative, E->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 (E->model == MPI_EC_WEIERSTRASS) { mpi_free (y); y = negative; } else { mpi_free (x); x = negative; } mpi_sub (sk->d, E->n, sk->d); /* d = order - d */ mpi_point_set (&sk->Q, 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); point_set (&sk->Q, &Q); 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 (sk->E.model != MPI_EC_MONTGOMERY) test_keys (sk, nbits - 64); else test_ecdh_only_keys (sk, nbits - 64, flags); 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 (ECC_secret_key *sk, unsigned int nbits) { ECC_public_key pk; 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_); pk.E = _gcry_ecc_curve_copy (sk->E); point_init (&pk.Q); point_set (&pk.Q, &sk->Q); _gcry_mpi_randomize (test, nbits, GCRY_WEAK_RANDOM); if (_gcry_ecc_ecdsa_sign (test, sk, r, s, 0, 0) ) log_fatal ("ECDSA operation: sign failed\n"); if (_gcry_ecc_ecdsa_verify (test, &pk, r, s)) { log_fatal ("ECDSA operation: sign, verify failed\n"); } if (DBG_CIPHER) log_debug ("ECDSA operation: sign, verify ok.\n"); point_free (&pk.Q); _gcry_ecc_curve_free (&pk.E); point_free (&R_); mpi_free (s); mpi_free (r); mpi_free (out); mpi_free (c); mpi_free (test); } static void test_ecdh_only_keys (ECC_secret_key *sk, unsigned int nbits, int flags) { ECC_public_key pk; gcry_mpi_t test; mpi_point_struct R_; gcry_mpi_t x0, x1; mpi_ec_t ec; if (DBG_CIPHER) log_debug ("Testing ECDH only key.\n"); point_init (&R_); pk.E = _gcry_ecc_curve_copy (sk->E); point_init (&pk.Q); point_set (&pk.Q, &sk->Q); if ((flags & PUBKEY_FLAG_DJB_TWEAK)) { char *rndbuf; test = mpi_new (256); rndbuf = _gcry_random_bytes (32, GCRY_WEAK_RANDOM); rndbuf[0] &= 0x7f; /* Clear bit 255. */ rndbuf[0] |= 0x40; /* Set bit 254. */ rndbuf[31] &= 0xf8; /* Clear bits 2..0 so that d mod 8 == 0 */ _gcry_mpi_set_buffer (test, rndbuf, 32, 0); xfree (rndbuf); } else { test = mpi_new (nbits); _gcry_mpi_randomize (test, nbits, GCRY_WEAK_RANDOM); } ec = _gcry_mpi_ec_p_internal_new (pk.E.model, pk.E.dialect, flags, pk.E.p, pk.E.a, pk.E.b); x0 = mpi_new (0); x1 = mpi_new (0); /* R_ = hkQ <=> R_ = hkdG */ _gcry_mpi_ec_mul_point (&R_, test, &pk.Q, ec); if (!(flags & PUBKEY_FLAG_DJB_TWEAK)) _gcry_mpi_ec_mul_point (&R_, 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, &pk.E.G, ec); _gcry_mpi_ec_mul_point (&R_, sk->d, &R_, ec); /* R_ = hdkG */ if (!(flags & PUBKEY_FLAG_DJB_TWEAK)) _gcry_mpi_ec_mul_point (&R_, 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); _gcry_mpi_ec_free (ec); point_free (&pk.Q); _gcry_ecc_curve_free (&pk.E); 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 (ECC_secret_key *sk, 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 (&sk->E.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 (sk->E.G.z, 0)) { if (DBG_CIPHER) log_debug ("Bad check: 'G' cannot be Point at Infinity!\n"); goto leave; } /* Check order of curve. */ if (sk->E.dialect != ECC_DIALECT_ED25519 && !(flags & PUBKEY_FLAG_DJB_TWEAK)) { _gcry_mpi_ec_mul_point (&Q, sk->E.n, &sk->E.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 (sk->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, &sk->E.G, sk->d)) { 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)) ; /* Fixme: EdDSA is special. */ else if (!mpi_cmp_ui (sk->Q.z, 1)) { /* Fast path if Q is already in affine coordinates. */ if (mpi_cmp (x1, sk->Q.x) || (y1 && mpi_cmp (y1, sk->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, &sk->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; unsigned int nbits; elliptic_curve_t E; ECC_secret_key sk; gcry_mpi_t Gx = NULL; gcry_mpi_t Gy = NULL; gcry_mpi_t Qx = NULL; gcry_mpi_t Qy = NULL; char *curve_name = NULL; gcry_sexp_t l1; mpi_ec_t ctx = NULL; gcry_sexp_t curve_info = NULL; gcry_sexp_t curve_flags = NULL; gcry_mpi_t base = NULL; gcry_mpi_t public = NULL; gcry_mpi_t secret = NULL; int flags = 0; memset (&E, 0, sizeof E); memset (&sk, 0, sizeof sk); rc = _gcry_pk_util_get_nbits (genparms, &nbits); if (rc) return rc; /* Parse the optional "curve" parameter. */ l1 = sexp_find_token (genparms, "curve", 0); if (l1) { curve_name = _gcry_sexp_nth_string (l1, 1); sexp_release (l1); if (!curve_name) return GPG_ERR_INV_OBJ; /* No curve name or value too large. */ } /* Parse the optional flags list. */ l1 = sexp_find_token (genparms, "flags", 0); if (l1) { rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL); sexp_release (l1); if (rc) goto leave; } /* Parse the deprecated optional transient-key flag. */ l1 = sexp_find_token (genparms, "transient-key", 0); if (l1) { flags |= PUBKEY_FLAG_TRANSIENT_KEY; sexp_release (l1); } /* NBITS is required if no curve name has been given. */ if (!nbits && !curve_name) return GPG_ERR_NO_OBJ; /* No NBITS parameter. */ rc = _gcry_ecc_fill_in_curve (nbits, curve_name, &E, &nbits); if (rc) goto leave; if (DBG_CIPHER) { log_debug ("ecgen curve info: %s/%s\n", _gcry_ecc_model2str (E.model), _gcry_ecc_dialect2str (E.dialect)); if (E.name) log_debug ("ecgen curve used: %s\n", E.name); log_printmpi ("ecgen curve p", E.p); log_printmpi ("ecgen curve a", E.a); log_printmpi ("ecgen curve b", E.b); log_printmpi ("ecgen curve n", E.n); log_printmpi ("ecgen curve h", E.h); log_printpnt ("ecgen curve G", &E.G, NULL); } ctx = _gcry_mpi_ec_p_internal_new (E.model, E.dialect, flags, E.p, E.a, E.b); if (E.model == MPI_EC_MONTGOMERY) rc = nist_generate_key (&sk, &E, ctx, flags, nbits, &Qx, NULL); else if ((flags & PUBKEY_FLAG_EDDSA)) rc = _gcry_ecc_eddsa_genkey (&sk, &E, ctx, flags); else rc = nist_generate_key (&sk, &E, ctx, flags, nbits, &Qx, &Qy); if (rc) goto leave; /* Copy data to the result. */ Gx = mpi_new (0); Gy = mpi_new (0); if (E.model != MPI_EC_MONTGOMERY) { if (_gcry_mpi_ec_get_affine (Gx, Gy, &sk.E.G, ctx)) log_fatal ("ecgen: Failed to get affine coordinates for %s\n", "G"); base = _gcry_ecc_ec2os (Gx, Gy, sk.E.p); } if ((sk.E.dialect == ECC_DIALECT_ED25519 || E.model == MPI_EC_MONTGOMERY) && !(flags & PUBKEY_FLAG_NOCOMP)) { unsigned char *encpk; unsigned int encpklen; if (E.model != MPI_EC_MONTGOMERY) /* (Gx and Gy are used as scratch variables) */ rc = _gcry_ecc_eddsa_encodepoint (&sk.Q, ctx, Gx, Gy, !!(flags & PUBKEY_FLAG_COMP), &encpk, &encpklen); else { encpk = _gcry_mpi_get_buffer_extra (Qx, nbits/8, -1, &encpklen, NULL); if (encpk == NULL) rc = gpg_err_code_from_syserror (); else { encpk[0] = 0x40; 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, &sk.Q, ctx)) log_fatal ("ecgen: Failed to get affine coordinates for %s\n", "Q"); } public = _gcry_ecc_ec2os (Qx, Qy, sk.E.p); } secret = sk.d; sk.d = NULL; if (E.name) { rc = sexp_build (&curve_info, NULL, "(curve %s)", E.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_EDDSA))? "(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) && E.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%m)(q%m)))" " (private-key" " (ecc%S%S(p%m)(a%m)(b%m)(g%m)(n%m)(h%m)(q%m)(d%m)))" " )", curve_info, curve_flags, sk.E.p, sk.E.a, sk.E.b, base, sk.E.n, sk.E.h, public, curve_info, curve_flags, sk.E.p, sk.E.a, sk.E.b, base, sk.E.n, sk.E.h, public, secret); 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, secret); if (rc) goto leave; if (DBG_CIPHER) { log_printmpi ("ecgen result p", sk.E.p); log_printmpi ("ecgen result a", sk.E.a); log_printmpi ("ecgen result b", sk.E.b); log_printmpi ("ecgen result G", base); log_printmpi ("ecgen result n", sk.E.n); log_printmpi ("ecgen result h", sk.E.h); log_printmpi ("ecgen result Q", public); log_printmpi ("ecgen result d", secret); if ((flags & PUBKEY_FLAG_EDDSA)) log_debug ("ecgen result using Ed25519+EdDSA\n"); } leave: mpi_free (secret); mpi_free (public); mpi_free (base); { _gcry_ecc_curve_free (&sk.E); point_free (&sk.Q); mpi_free (sk.d); } _gcry_ecc_curve_free (&E); mpi_free (Gx); mpi_free (Gy); mpi_free (Qx); mpi_free (Qy); _gcry_mpi_ec_free (ctx); xfree (curve_name); 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; gcry_sexp_t l1 = NULL; int flags = 0; char *curvename = NULL; gcry_mpi_t mpi_g = NULL; gcry_mpi_t mpi_q = NULL; ECC_secret_key sk; mpi_ec_t ec = NULL; memset (&sk, 0, sizeof sk); /* 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?h?/q?+d", &sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n, &sk.E.h, &mpi_q, &sk.d, NULL); else rc = sexp_extract_param (keyparms, NULL, "/q?+d", &mpi_q, &sk.d, NULL); if (rc) goto leave; /* Add missing parameters using the optional curve parameter. */ sexp_release (l1); l1 = sexp_find_token (keyparms, "curve", 5); if (l1) { curvename = sexp_nth_string (l1, 1); if (curvename) { rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL); if (rc) goto leave; } } if (mpi_g) { if (!sk.E.G.x) point_init (&sk.E.G); rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g); 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) { sk.E.model = ((flags & PUBKEY_FLAG_EDDSA) ? MPI_EC_EDWARDS : MPI_EC_WEIERSTRASS); sk.E.dialect = ((flags & PUBKEY_FLAG_EDDSA) ? ECC_DIALECT_ED25519 : ECC_DIALECT_STANDARD); if (!sk.E.h) sk.E.h = mpi_const (MPI_C_ONE); } if (DBG_CIPHER) { log_debug ("ecc_testkey inf: %s/%s\n", _gcry_ecc_model2str (sk.E.model), _gcry_ecc_dialect2str (sk.E.dialect)); if (sk.E.name) log_debug ("ecc_testkey nam: %s\n", sk.E.name); log_printmpi ("ecc_testkey p", sk.E.p); log_printmpi ("ecc_testkey a", sk.E.a); log_printmpi ("ecc_testkey b", sk.E.b); log_printpnt ("ecc_testkey g", &sk.E.G, NULL); log_printmpi ("ecc_testkey n", sk.E.n); log_printmpi ("ecc_testkey h", sk.E.h); log_printmpi ("ecc_testkey q", mpi_q); if (!fips_mode ()) log_printmpi ("ecc_testkey d", sk.d); } if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d) { rc = GPG_ERR_NO_OBJ; goto leave; } ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags, sk.E.p, sk.E.a, sk.E.b); if (mpi_q) { point_init (&sk.Q); if (ec->dialect == ECC_DIALECT_ED25519) rc = _gcry_ecc_eddsa_decodepoint (mpi_q, ec, &sk.Q, NULL, NULL); else if (ec->model == MPI_EC_MONTGOMERY) rc = _gcry_ecc_mont_decodepoint (mpi_q, ec, &sk.Q); else rc = _gcry_ecc_os2ec (&sk.Q, mpi_q); if (rc) goto leave; } else { /* The secret key test requires Q. */ rc = GPG_ERR_NO_OBJ; goto leave; } if (check_secret_key (&sk, ec, flags)) rc = GPG_ERR_BAD_SECKEY; leave: _gcry_mpi_ec_free (ec); _gcry_mpi_release (sk.E.p); _gcry_mpi_release (sk.E.a); _gcry_mpi_release (sk.E.b); _gcry_mpi_release (mpi_g); point_free (&sk.E.G); _gcry_mpi_release (sk.E.n); _gcry_mpi_release (sk.E.h); _gcry_mpi_release (mpi_q); point_free (&sk.Q); _gcry_mpi_release (sk.d); xfree (curvename); sexp_release (l1); 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_sexp_t l1 = NULL; char *curvename = NULL; gcry_mpi_t mpi_g = NULL; gcry_mpi_t mpi_q = NULL; ECC_secret_key sk; gcry_mpi_t sig_r = NULL; gcry_mpi_t sig_s = NULL; memset (&sk, 0, sizeof sk); _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_SIGN, 0); /* 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); /* * Extract the key. */ if ((ctx.flags & PUBKEY_FLAG_PARAM)) rc = sexp_extract_param (keyparms, NULL, "-p?a?b?g?n?h?/q?+d", &sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n, &sk.E.h, &mpi_q, &sk.d, NULL); else rc = sexp_extract_param (keyparms, NULL, "/q?+d", &mpi_q, &sk.d, NULL); if (rc) goto leave; if (mpi_g) { point_init (&sk.E.G); rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g); if (rc) goto leave; } /* Add missing parameters using the optional curve parameter. */ l1 = sexp_find_token (keyparms, "curve", 5); if (l1) { curvename = sexp_nth_string (l1, 1); if (curvename) { rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL); 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) { sk.E.model = ((ctx.flags & PUBKEY_FLAG_EDDSA) ? MPI_EC_EDWARDS : MPI_EC_WEIERSTRASS); sk.E.dialect = ((ctx.flags & PUBKEY_FLAG_EDDSA) ? ECC_DIALECT_ED25519 : ECC_DIALECT_STANDARD); if (!sk.E.h) sk.E.h = mpi_const (MPI_C_ONE); } if (DBG_CIPHER) { log_debug ("ecc_sign info: %s/%s%s\n", _gcry_ecc_model2str (sk.E.model), _gcry_ecc_dialect2str (sk.E.dialect), (ctx.flags & PUBKEY_FLAG_EDDSA)? "+EdDSA":""); if (sk.E.name) log_debug ("ecc_sign name: %s\n", sk.E.name); log_printmpi ("ecc_sign p", sk.E.p); log_printmpi ("ecc_sign a", sk.E.a); log_printmpi ("ecc_sign b", sk.E.b); log_printpnt ("ecc_sign g", &sk.E.G, NULL); log_printmpi ("ecc_sign n", sk.E.n); log_printmpi ("ecc_sign h", sk.E.h); log_printmpi ("ecc_sign q", mpi_q); if (!fips_mode ()) log_printmpi ("ecc_sign d", sk.d); } if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d) { rc = GPG_ERR_NO_OBJ; goto leave; } 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, &sk, sig_r, sig_s, ctx.hash_algo, mpi_q); 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, &sk, sig_r, sig_s); if (!rc) rc = sexp_build (r_sig, NULL, "(sig-val(gost(r%M)(s%M)))", sig_r, sig_s); } else { rc = _gcry_ecc_ecdsa_sign (data, &sk, 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 (sk.E.p); _gcry_mpi_release (sk.E.a); _gcry_mpi_release (sk.E.b); _gcry_mpi_release (mpi_g); point_free (&sk.E.G); _gcry_mpi_release (sk.E.n); _gcry_mpi_release (sk.E.h); _gcry_mpi_release (mpi_q); point_free (&sk.Q); _gcry_mpi_release (sk.d); _gcry_mpi_release (sig_r); _gcry_mpi_release (sig_s); xfree (curvename); _gcry_mpi_release (data); sexp_release (l1); _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; char *curvename = NULL; gcry_mpi_t mpi_g = NULL; gcry_mpi_t mpi_q = NULL; gcry_mpi_t sig_r = NULL; gcry_mpi_t sig_s = NULL; gcry_mpi_t data = NULL; ECC_public_key pk; int sigflags; memset (&pk, 0, sizeof pk); _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_VERIFY, ecc_get_nbits (s_keyparms)); /* 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); /* * 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; } /* * Extract the key. */ if ((ctx.flags & PUBKEY_FLAG_PARAM)) rc = sexp_extract_param (s_keyparms, NULL, "-p?a?b?g?n?h?/q", &pk.E.p, &pk.E.a, &pk.E.b, &mpi_g, &pk.E.n, &pk.E.h, &mpi_q, NULL); else rc = sexp_extract_param (s_keyparms, NULL, "/q", &mpi_q, NULL); if (rc) goto leave; if (mpi_g) { point_init (&pk.E.G); rc = _gcry_ecc_os2ec (&pk.E.G, mpi_g); if (rc) goto leave; } /* Add missing parameters using the optional curve parameter. */ sexp_release (l1); l1 = sexp_find_token (s_keyparms, "curve", 5); if (l1) { curvename = sexp_nth_string (l1, 1); if (curvename) { rc = _gcry_ecc_fill_in_curve (0, curvename, &pk.E, NULL); 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) { pk.E.model = ((sigflags & PUBKEY_FLAG_EDDSA) ? MPI_EC_EDWARDS : MPI_EC_WEIERSTRASS); pk.E.dialect = ((sigflags & PUBKEY_FLAG_EDDSA) ? ECC_DIALECT_ED25519 : ECC_DIALECT_STANDARD); if (!pk.E.h) pk.E.h = mpi_const (MPI_C_ONE); } if (DBG_CIPHER) { log_debug ("ecc_verify info: %s/%s%s\n", _gcry_ecc_model2str (pk.E.model), _gcry_ecc_dialect2str (pk.E.dialect), (sigflags & PUBKEY_FLAG_EDDSA)? "+EdDSA":""); if (pk.E.name) log_debug ("ecc_verify name: %s\n", pk.E.name); log_printmpi ("ecc_verify p", pk.E.p); log_printmpi ("ecc_verify a", pk.E.a); log_printmpi ("ecc_verify b", pk.E.b); log_printpnt ("ecc_verify g", &pk.E.G, NULL); log_printmpi ("ecc_verify n", pk.E.n); log_printmpi ("ecc_verify h", pk.E.h); log_printmpi ("ecc_verify q", mpi_q); } if (!pk.E.p || !pk.E.a || !pk.E.b || !pk.E.G.x || !pk.E.n || !pk.E.h || !mpi_q) { rc = GPG_ERR_NO_OBJ; goto leave; } /* * Verify the signature. */ if ((sigflags & PUBKEY_FLAG_EDDSA)) { rc = _gcry_ecc_eddsa_verify (data, &pk, sig_r, sig_s, ctx.hash_algo, mpi_q); } else if ((sigflags & PUBKEY_FLAG_GOST)) { point_init (&pk.Q); rc = _gcry_ecc_os2ec (&pk.Q, mpi_q); if (rc) goto leave; rc = _gcry_ecc_gost_verify (data, &pk, sig_r, sig_s); } else { point_init (&pk.Q); if (pk.E.dialect == ECC_DIALECT_ED25519) { mpi_ec_t ec; /* Fixme: Factor the curve context setup out of eddsa_verify and ecdsa_verify. So that we don't do it twice. */ ec = _gcry_mpi_ec_p_internal_new (pk.E.model, pk.E.dialect, 0, pk.E.p, pk.E.a, pk.E.b); rc = _gcry_ecc_eddsa_decodepoint (mpi_q, ec, &pk.Q, NULL, NULL); _gcry_mpi_ec_free (ec); } else { rc = _gcry_ecc_os2ec (&pk.Q, mpi_q); } if (rc) goto leave; if (mpi_is_opaque (data)) { const void *abuf; unsigned int abits, qbits; gcry_mpi_t a; qbits = mpi_get_nbits (pk.E.n); abuf = mpi_get_opaque (data, &abits); rc = _gcry_mpi_scan (&a, GCRYMPI_FMT_USG, abuf, (abits+7)/8, NULL); if (!rc) { if (abits > qbits) mpi_rshift (a, a, abits - qbits); rc = _gcry_ecc_ecdsa_verify (a, &pk, sig_r, sig_s); _gcry_mpi_release (a); } } else rc = _gcry_ecc_ecdsa_verify (data, &pk, sig_r, sig_s); } leave: _gcry_mpi_release (pk.E.p); _gcry_mpi_release (pk.E.a); _gcry_mpi_release (pk.E.b); _gcry_mpi_release (mpi_g); point_free (&pk.E.G); _gcry_mpi_release (pk.E.n); _gcry_mpi_release (pk.E.h); _gcry_mpi_release (mpi_q); point_free (&pk.Q); _gcry_mpi_release (data); _gcry_mpi_release (sig_r); _gcry_mpi_release (sig_s); xfree (curvename); 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_sexp_t l1 = NULL; char *curvename = NULL; gcry_mpi_t mpi_g = NULL; gcry_mpi_t mpi_q = NULL; gcry_mpi_t mpi_s = NULL; gcry_mpi_t mpi_e = NULL; gcry_mpi_t data = NULL; ECC_public_key pk; mpi_ec_t ec = NULL; int flags = 0; memset (&pk, 0, sizeof pk); _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_ENCRYPT, (nbits = ecc_get_nbits (keyparms))); /* 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; } sexp_release (l1); l1 = NULL; /* * Extract the data. */ rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx); if (rc) goto leave; if (mpi_is_opaque (data)) { rc = GPG_ERR_INV_DATA; goto leave; } /* * Extract the key. */ rc = sexp_extract_param (keyparms, NULL, (flags & PUBKEY_FLAG_DJB_TWEAK)? "-p?a?b?g?n?h?/q" : "-p?a?b?g?n?h?+q", &pk.E.p, &pk.E.a, &pk.E.b, &mpi_g, &pk.E.n, &pk.E.h, &mpi_q, NULL); if (rc) goto leave; if (mpi_g) { point_init (&pk.E.G); rc = _gcry_ecc_os2ec (&pk.E.G, mpi_g); if (rc) goto leave; } /* Add missing parameters using the optional curve parameter. */ l1 = sexp_find_token (keyparms, "curve", 5); if (l1) { curvename = sexp_nth_string (l1, 1); if (curvename) { rc = _gcry_ecc_fill_in_curve (0, curvename, &pk.E, NULL); if (rc) goto leave; } } /* Guess required fields if a curve parameter has not been given. */ if (!curvename) { pk.E.model = MPI_EC_WEIERSTRASS; pk.E.dialect = ECC_DIALECT_STANDARD; if (!pk.E.h) pk.E.h = mpi_const (MPI_C_ONE); } /* * 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; i < mpi_get_nbits (pk.E.h) - 1; i++) mpi_clear_bit (data, i); mpi_set_highbit (data, mpi_get_nbits (pk.E.p) - 1); } if (DBG_CIPHER) log_mpidump ("ecc_encrypt data", data); if (DBG_CIPHER) { log_debug ("ecc_encrypt info: %s/%s\n", _gcry_ecc_model2str (pk.E.model), _gcry_ecc_dialect2str (pk.E.dialect)); if (pk.E.name) log_debug ("ecc_encrypt name: %s\n", pk.E.name); log_printmpi ("ecc_encrypt p", pk.E.p); log_printmpi ("ecc_encrypt a", pk.E.a); log_printmpi ("ecc_encrypt b", pk.E.b); log_printpnt ("ecc_encrypt g", &pk.E.G, NULL); log_printmpi ("ecc_encrypt n", pk.E.n); log_printmpi ("ecc_encrypt h", pk.E.h); log_printmpi ("ecc_encrypt q", mpi_q); } if (!pk.E.p || !pk.E.a || !pk.E.b || !pk.E.G.x || !pk.E.n || !pk.E.h || !mpi_q) { rc = GPG_ERR_NO_OBJ; goto leave; } /* Compute the encrypted value. */ ec = _gcry_mpi_ec_p_internal_new (pk.E.model, pk.E.dialect, flags, pk.E.p, pk.E.a, pk.E.b); /* Convert the public key. */ if (mpi_q) { point_init (&pk.Q); if (ec->model == MPI_EC_MONTGOMERY) rc = _gcry_ecc_mont_decodepoint (mpi_q, ec, &pk.Q); else rc = _gcry_ecc_os2ec (&pk.Q, mpi_q); if (rc) 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; 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, &pk.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 (!(flags & PUBKEY_FLAG_DJB_TWEAK)) { /* It's not for X25519, then, the input data was simply wrong. */ rc = GPG_ERR_INV_DATA; goto leave; } } if (y) mpi_s = _gcry_ecc_ec2os (x, y, pk.E.p); else { rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1, &rawmpilen, NULL); if (!rawmpi) rc = gpg_err_code_from_syserror (); else { rawmpi[0] = 0x40; rawmpilen++; mpi_s = mpi_new (0); mpi_set_opaque (mpi_s, rawmpi, rawmpilen*8); } } /* R = kG */ _gcry_mpi_ec_mul_point (&R, data, &pk.E.G, ec); if (_gcry_mpi_ec_get_affine (x, y, &R, ec)) { rc = GPG_ERR_INV_DATA; goto leave; } if (y) mpi_e = _gcry_ecc_ec2os (x, y, pk.E.p); else { rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1, &rawmpilen, NULL); if (!rawmpi) rc = gpg_err_code_from_syserror (); else { rawmpi[0] = 0x40; rawmpilen++; mpi_e = mpi_new (0); mpi_set_opaque (mpi_e, rawmpi, rawmpilen*8); } } mpi_free (x); mpi_free (y); point_free (&R); } if (!rc) rc = sexp_build (r_ciph, NULL, "(enc-val(ecdh(s%m)(e%m)))", mpi_s, mpi_e); leave: _gcry_mpi_release (pk.E.p); _gcry_mpi_release (pk.E.a); _gcry_mpi_release (pk.E.b); _gcry_mpi_release (mpi_g); point_free (&pk.E.G); _gcry_mpi_release (pk.E.n); _gcry_mpi_release (pk.E.h); _gcry_mpi_release (mpi_q); point_free (&pk.Q); _gcry_mpi_release (data); _gcry_mpi_release (mpi_s); _gcry_mpi_release (mpi_e); xfree (curvename); sexp_release (l1); _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; ECC_secret_key sk; gcry_mpi_t mpi_g = NULL; char *curvename = NULL; mpi_ec_t ec = NULL; mpi_point_struct kG; mpi_point_struct R; gcry_mpi_t r = NULL; int flags = 0; memset (&sk, 0, sizeof sk); point_init (&kG); point_init (&R); _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, (nbits = ecc_get_nbits (keyparms))); /* 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; } sexp_release (l1); l1 = NULL; /* * Extract the data. */ rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx); if (rc) goto leave; 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 (mpi_is_opaque (data_e)) { rc = GPG_ERR_INV_DATA; goto leave; } /* * Extract the key. */ rc = sexp_extract_param (keyparms, NULL, "-p?a?b?g?n?h?+d", &sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n, &sk.E.h, &sk.d, NULL); if (rc) goto leave; if (mpi_g) { point_init (&sk.E.G); rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g); if (rc) goto leave; } /* Add missing parameters using the optional curve parameter. */ sexp_release (l1); l1 = sexp_find_token (keyparms, "curve", 5); if (l1) { curvename = sexp_nth_string (l1, 1); if (curvename) { rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL); if (rc) goto leave; } } /* Guess required fields if a curve parameter has not been given. */ if (!curvename) { sk.E.model = MPI_EC_WEIERSTRASS; sk.E.dialect = ECC_DIALECT_STANDARD; if (!sk.E.h) sk.E.h = mpi_const (MPI_C_ONE); } if (DBG_CIPHER) { log_debug ("ecc_decrypt info: %s/%s\n", _gcry_ecc_model2str (sk.E.model), _gcry_ecc_dialect2str (sk.E.dialect)); if (sk.E.name) log_debug ("ecc_decrypt name: %s\n", sk.E.name); log_printmpi ("ecc_decrypt p", sk.E.p); log_printmpi ("ecc_decrypt a", sk.E.a); log_printmpi ("ecc_decrypt b", sk.E.b); log_printpnt ("ecc_decrypt g", &sk.E.G, NULL); log_printmpi ("ecc_decrypt n", sk.E.n); log_printmpi ("ecc_decrypt h", sk.E.h); if (!fips_mode ()) log_printmpi ("ecc_decrypt d", sk.d); } if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d) { rc = GPG_ERR_NO_OBJ; goto leave; } ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags, sk.E.p, sk.E.a, sk.E.b); /* * Compute the plaintext. */ if (ec->model == MPI_EC_MONTGOMERY) rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG); else rc = _gcry_ecc_os2ec (&kG, data_e); if (rc) goto leave; if (DBG_CIPHER) log_printpnt ("ecc_decrypt kG", &kG, NULL); - if (!(flags & PUBKEY_FLAG_DJB_TWEAK) + if ((flags & PUBKEY_FLAG_DJB_TWEAK)) + { /* For X25519, by its definition, validation should not be done. */ - && !_gcry_mpi_ec_curve_point (&kG, ec)) + /* (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, sk.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 SK.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, sk.E.p); else { unsigned char *rawmpi; unsigned int rawmpilen; rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1, &rawmpilen, NULL); if (!rawmpi) { rc = gpg_err_code_from_syserror (); goto leave; } else { rawmpi[0] = 0x40; rawmpilen++; 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 (sk.E.p); _gcry_mpi_release (sk.E.a); _gcry_mpi_release (sk.E.b); _gcry_mpi_release (mpi_g); point_free (&sk.E.G); _gcry_mpi_release (sk.E.n); _gcry_mpi_release (sk.E.h); _gcry_mpi_release (sk.d); _gcry_mpi_release (data_e); xfree (curvename); 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 7 static const char names[N_COMPONENTS] = "pabgnhq"; 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; /* 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)) { if ((flags & PUBKEY_FLAG_DJB_TWEAK)) rc = sexp_extract_param (keyparms, NULL, "p?a?b?g?n?h?/q", &values[0], &values[1], &values[2], &values[3], &values[4], &values[5], &values[6], NULL); else rc = sexp_extract_param (keyparms, NULL, "p?a?b?g?n?h?q", &values[0], &values[1], &values[2], &values[3], &values[4], &values[5], &values[6], NULL); } else { if ((flags & PUBKEY_FLAG_DJB_TWEAK)) rc = sexp_extract_param (keyparms, NULL, "/q", &values[6], NULL); else rc = sexp_extract_param (keyparms, NULL, "q", &values[6], 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], &values[5]); 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); if (!values[5]) values[5] = mpi_const (MPI_C_ONE); } /* 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_DJB_TWEAK)) { rc = _gcry_ecc_eddsa_ensure_compact (values[6], 256); if (rc) goto leave; } /* Hash them all. */ for (idx = 0; idx < N_COMPONENTS; idx++) { char buf[30]; if (idx == 5) continue; /* Skip cofactor. */ if (mpi_is_opaque (values[idx])) { const unsigned char *raw; unsigned int n; 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); } else { unsigned char *rawmpi; unsigned int rawmpilen; rawmpi = _gcry_mpi_get_buffer (values[idx], 0, &rawmpilen, NULL); if (!rawmpi) { 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); } } 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 || !ec->h) 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, NULL, NULL); /* 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 { 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%m)(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%m)(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", "sw", "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/mpi/ec.c b/mpi/ec.c index a0f73575..4c166030 100644 --- a/mpi/ec.c +++ b/mpi/ec.c @@ -1,1574 +1,1619 @@ /* ec.c - Elliptic Curve functions * Copyright (C) 2007 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 "mpi-internal.h" #include "longlong.h" #include "g10lib.h" #include "context.h" #include "ec-context.h" #include "ec-internal.h" #define point_init(a) _gcry_mpi_point_init ((a)) #define point_free(a) _gcry_mpi_point_free_parts ((a)) /* Print a point using the log functions. If CTX is not NULL affine coordinates will be printed. */ void _gcry_mpi_point_log (const char *name, mpi_point_t point, mpi_ec_t ctx) { gcry_mpi_t x, y; char buf[100]; if (!point) { snprintf (buf, sizeof buf - 1, "%s.*", name); log_mpidump (buf, NULL); return; } snprintf (buf, sizeof buf - 1, "%s.X", name); if (ctx) { x = mpi_new (0); y = mpi_new (0); } if (!ctx || _gcry_mpi_ec_get_affine (x, y, point, ctx)) { log_mpidump (buf, point->x); buf[strlen(buf)-1] = 'Y'; log_mpidump (buf, point->y); buf[strlen(buf)-1] = 'Z'; log_mpidump (buf, point->z); } else { buf[strlen(buf)-1] = 'x'; log_mpidump (buf, x); buf[strlen(buf)-1] = 'y'; log_mpidump (buf, y); } if (ctx) { _gcry_mpi_release (x); _gcry_mpi_release (y); } } /* Create a new point option. NBITS gives the size in bits of one coordinate; it is only used to pre-allocate some resources and might also be passed as 0 to use a default value. */ mpi_point_t _gcry_mpi_point_new (unsigned int nbits) { mpi_point_t p; (void)nbits; /* Currently not used. */ p = xmalloc (sizeof *p); _gcry_mpi_point_init (p); return p; } /* Release the point object P. P may be NULL. */ void _gcry_mpi_point_release (mpi_point_t p) { if (p) { _gcry_mpi_point_free_parts (p); xfree (p); } } /* Initialize the fields of a point object. gcry_mpi_point_free_parts may be used to release the fields. */ void _gcry_mpi_point_init (mpi_point_t p) { p->x = mpi_new (0); p->y = mpi_new (0); p->z = mpi_new (0); } /* Release the parts of a point object. */ void _gcry_mpi_point_free_parts (mpi_point_t p) { mpi_free (p->x); p->x = NULL; mpi_free (p->y); p->y = NULL; mpi_free (p->z); p->z = NULL; } /* Set the value from S into D. */ static 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); } /* Return a copy of POINT. */ gcry_mpi_point_t _gcry_mpi_point_copy (gcry_mpi_point_t point) { mpi_point_t newpoint; newpoint = _gcry_mpi_point_new (0); if (point) point_set (newpoint, point); return newpoint; } static void point_resize (mpi_point_t p, mpi_ec_t ctx) { /* * For now, we allocate enough limbs for our EC computation of ec_*. * Once we will improve ec_* to be constant size (and constant * time), NLIMBS can be ctx->p->nlimbs. */ size_t nlimbs = 2*ctx->p->nlimbs+1; mpi_resize (p->x, nlimbs); if (ctx->model != MPI_EC_MONTGOMERY) mpi_resize (p->y, nlimbs); mpi_resize (p->z, nlimbs); } static void point_swap_cond (mpi_point_t d, mpi_point_t s, unsigned long swap, mpi_ec_t ctx) { mpi_swap_cond (d->x, s->x, swap); if (ctx->model != MPI_EC_MONTGOMERY) mpi_swap_cond (d->y, s->y, swap); mpi_swap_cond (d->z, s->z, swap); } /* Set the projective coordinates from POINT into X, Y, and Z. If a coordinate is not required, X, Y, or Z may be passed as NULL. */ void _gcry_mpi_point_get (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, mpi_point_t point) { if (x) mpi_set (x, point->x); if (y) mpi_set (y, point->y); if (z) mpi_set (z, point->z); } /* Set the projective coordinates from POINT into X, Y, and Z and release POINT. If a coordinate is not required, X, Y, or Z may be passed as NULL. */ void _gcry_mpi_point_snatch_get (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, mpi_point_t point) { mpi_snatch (x, point->x); mpi_snatch (y, point->y); mpi_snatch (z, point->z); xfree (point); } /* Set the projective coordinates from X, Y, and Z into POINT. If a coordinate is given as NULL, the value 0 is stored into point. If POINT is given as NULL a new point object is allocated. Returns POINT or the newly allocated point object. */ mpi_point_t _gcry_mpi_point_set (mpi_point_t point, gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z) { if (!point) point = mpi_point_new (0); if (x) mpi_set (point->x, x); else mpi_clear (point->x); if (y) mpi_set (point->y, y); else mpi_clear (point->y); if (z) mpi_set (point->z, z); else mpi_clear (point->z); return point; } /* Set the projective coordinates from X, Y, and Z into POINT. If a coordinate is given as NULL, the value 0 is stored into point. If POINT is given as NULL a new point object is allocated. The coordinates X, Y, and Z are released. Returns POINT or the newly allocated point object. */ mpi_point_t _gcry_mpi_point_snatch_set (mpi_point_t point, gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z) { if (!point) point = mpi_point_new (0); if (x) mpi_snatch (point->x, x); else mpi_clear (point->x); if (y) mpi_snatch (point->y, y); else mpi_clear (point->y); if (z) mpi_snatch (point->z, z); else mpi_clear (point->z); return point; } /* W = W mod P. */ static void ec_mod (gcry_mpi_t w, mpi_ec_t ec) { if (0 && ec->dialect == ECC_DIALECT_ED25519) _gcry_mpi_ec_ed25519_mod (w); else if (ec->t.p_barrett) _gcry_mpi_mod_barrett (w, w, ec->t.p_barrett); else _gcry_mpi_mod (w, w, ec->p); } static void ec_addm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, mpi_ec_t ctx) { mpi_add (w, u, v); ec_mod (w, ctx); } static void ec_subm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, mpi_ec_t ec) { mpi_sub (w, u, v); while (w->sign) mpi_add (w, w, ec->p); /*ec_mod (w, ec);*/ } static void ec_mulm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, mpi_ec_t ctx) { mpi_mul (w, u, v); ec_mod (w, ctx); } /* W = 2 * U mod P. */ static void ec_mul2 (gcry_mpi_t w, gcry_mpi_t u, mpi_ec_t ctx) { mpi_lshift (w, u, 1); ec_mod (w, ctx); } static void ec_powm (gcry_mpi_t w, const gcry_mpi_t b, const gcry_mpi_t e, mpi_ec_t ctx) { mpi_powm (w, b, e, ctx->p); /* _gcry_mpi_abs (w); */ } /* Shortcut for ec_powm (B, B, mpi_const (MPI_C_TWO), ctx); for easier optimization. */ static void ec_pow2 (gcry_mpi_t w, const gcry_mpi_t b, mpi_ec_t ctx) { /* Using mpi_mul is slightly faster (at least on amd64). */ /* mpi_powm (w, b, mpi_const (MPI_C_TWO), ctx->p); */ ec_mulm (w, b, b, ctx); } /* Shortcut for ec_powm (B, B, mpi_const (MPI_C_THREE), ctx); for easier optimization. */ static void ec_pow3 (gcry_mpi_t w, const gcry_mpi_t b, mpi_ec_t ctx) { mpi_powm (w, b, mpi_const (MPI_C_THREE), ctx->p); } static void ec_invm (gcry_mpi_t x, gcry_mpi_t a, mpi_ec_t ctx) { if (!mpi_invm (x, a, ctx->p)) { log_error ("ec_invm: inverse does not exist:\n"); log_mpidump (" a", a); log_mpidump (" p", ctx->p); } } /* Force recomputation of all helper variables. */ void _gcry_mpi_ec_get_reset (mpi_ec_t ec) { ec->t.valid.a_is_pminus3 = 0; ec->t.valid.two_inv_p = 0; } /* Accessor for helper variable. */ static int ec_get_a_is_pminus3 (mpi_ec_t ec) { gcry_mpi_t tmp; if (!ec->t.valid.a_is_pminus3) { ec->t.valid.a_is_pminus3 = 1; tmp = mpi_alloc_like (ec->p); mpi_sub_ui (tmp, ec->p, 3); ec->t.a_is_pminus3 = !mpi_cmp (ec->a, tmp); mpi_free (tmp); } return ec->t.a_is_pminus3; } /* Accessor for helper variable. */ static gcry_mpi_t ec_get_two_inv_p (mpi_ec_t ec) { if (!ec->t.valid.two_inv_p) { ec->t.valid.two_inv_p = 1; if (!ec->t.two_inv_p) ec->t.two_inv_p = mpi_alloc (0); ec_invm (ec->t.two_inv_p, mpi_const (MPI_C_TWO), ec); } return ec->t.two_inv_p; } +static const char *curve25519_bad_points[] = { + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x00b8495f16056286fdb1329ceb8d09da6ac49ff1fae35616aeb8413b7c7aebe0", + "0x57119fd0dd4e22d8868e1c58c45c44045bef839c55b1d0b1248c50a3bc959c5f", + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec", + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed", + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffee", + NULL +}; + +static gcry_mpi_t +scanval (const char *string) +{ + gpg_err_code_t rc; + gcry_mpi_t val; + + rc = _gcry_mpi_scan (&val, GCRYMPI_FMT_HEX, string, 0, NULL); + if (rc) + log_fatal ("scanning ECC parameter failed: %s\n", gpg_strerror (rc)); + return val; +} + /* This function initialized a context for elliptic curve based on the field GF(p). P is the prime specifying this field, A is the first coefficient. CTX is expected to be zeroized. */ static void ec_p_init (mpi_ec_t ctx, enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b) { int i; static int use_barrett; if (!use_barrett) { if (getenv ("GCRYPT_BARRETT")) use_barrett = 1; else use_barrett = -1; } /* Fixme: Do we want to check some constraints? e.g. a < p */ ctx->model = model; ctx->dialect = dialect; ctx->flags = flags; if (dialect == ECC_DIALECT_ED25519) ctx->nbits = 256; else ctx->nbits = mpi_get_nbits (p); ctx->p = mpi_copy (p); ctx->a = mpi_copy (a); ctx->b = mpi_copy (b); ctx->t.p_barrett = use_barrett > 0? _gcry_mpi_barrett_init (ctx->p, 0):NULL; _gcry_mpi_ec_get_reset (ctx); - /* Allocate scratch variables. */ - for (i=0; i< DIM(ctx->t.scratch); i++) - ctx->t.scratch[i] = mpi_alloc_like (ctx->p); + if (model == MPI_EC_MONTGOMERY) + { + for (i=0; i< DIM(ctx->t.scratch) && curve25519_bad_points[i]; i++) + ctx->t.scratch[i] = scanval (curve25519_bad_points[i]); + } + else + { + /* Allocate scratch variables. */ + for (i=0; i< DIM(ctx->t.scratch); i++) + ctx->t.scratch[i] = mpi_alloc_like (ctx->p); + } /* Prepare for fast reduction. */ /* FIXME: need a test for NIST values. However it does not gain us any real advantage, for 384 bits it is actually slower than using mpi_mulm. */ /* ctx->nist_nbits = mpi_get_nbits (ctx->p); */ /* if (ctx->nist_nbits == 192) */ /* { */ /* for (i=0; i < 4; i++) */ /* ctx->s[i] = mpi_new (192); */ /* ctx->c = mpi_new (192*2); */ /* } */ /* else if (ctx->nist_nbits == 384) */ /* { */ /* for (i=0; i < 10; i++) */ /* ctx->s[i] = mpi_new (384); */ /* ctx->c = mpi_new (384*2); */ /* } */ } static void ec_deinit (void *opaque) { mpi_ec_t ctx = opaque; int i; _gcry_mpi_barrett_free (ctx->t.p_barrett); /* Domain parameter. */ mpi_free (ctx->p); mpi_free (ctx->a); mpi_free (ctx->b); _gcry_mpi_point_release (ctx->G); mpi_free (ctx->n); mpi_free (ctx->h); /* The key. */ _gcry_mpi_point_release (ctx->Q); mpi_free (ctx->d); /* Private data of ec.c. */ mpi_free (ctx->t.two_inv_p); for (i=0; i< DIM(ctx->t.scratch); i++) mpi_free (ctx->t.scratch[i]); /* if (ctx->nist_nbits == 192) */ /* { */ /* for (i=0; i < 4; i++) */ /* mpi_free (ctx->s[i]); */ /* mpi_free (ctx->c); */ /* } */ /* else if (ctx->nist_nbits == 384) */ /* { */ /* for (i=0; i < 10; i++) */ /* mpi_free (ctx->s[i]); */ /* mpi_free (ctx->c); */ /* } */ } /* This function returns a new context for elliptic curve based on the field GF(p). P is the prime specifying this field, A is the first coefficient, B is the second coefficient, and MODEL is the model for the curve. This function is only used within Libgcrypt and not part of the public API. This context needs to be released using _gcry_mpi_ec_free. */ mpi_ec_t _gcry_mpi_ec_p_internal_new (enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b) { mpi_ec_t ctx; ctx = xcalloc (1, sizeof *ctx); ec_p_init (ctx, model, dialect, flags, p, a, b); return ctx; } /* This is a variant of _gcry_mpi_ec_p_internal_new which returns an public context and does some error checking on the supplied arguments. On success the new context is stored at R_CTX and 0 is returned; on error NULL is stored at R_CTX and an error code is returned. The context needs to be released using gcry_ctx_release. */ gpg_err_code_t _gcry_mpi_ec_p_new (gcry_ctx_t *r_ctx, enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b) { gcry_ctx_t ctx; mpi_ec_t ec; *r_ctx = NULL; if (!p || !a) return GPG_ERR_EINVAL; ctx = _gcry_ctx_alloc (CONTEXT_TYPE_EC, sizeof *ec, ec_deinit); if (!ctx) return gpg_err_code_from_syserror (); ec = _gcry_ctx_get_pointer (ctx, CONTEXT_TYPE_EC); ec_p_init (ec, model, dialect, flags, p, a, b); *r_ctx = ctx; return 0; } void _gcry_mpi_ec_free (mpi_ec_t ctx) { if (ctx) { ec_deinit (ctx); xfree (ctx); } } gcry_mpi_t _gcry_mpi_ec_get_mpi (const char *name, gcry_ctx_t ctx, int copy) { mpi_ec_t ec = _gcry_ctx_get_pointer (ctx, CONTEXT_TYPE_EC); return _gcry_ecc_get_mpi (name, ec, copy); } gcry_mpi_point_t _gcry_mpi_ec_get_point (const char *name, gcry_ctx_t ctx, int copy) { mpi_ec_t ec = _gcry_ctx_get_pointer (ctx, CONTEXT_TYPE_EC); (void)copy; /* Not used. */ return _gcry_ecc_get_point (name, ec); } gpg_err_code_t _gcry_mpi_ec_set_mpi (const char *name, gcry_mpi_t newvalue, gcry_ctx_t ctx) { mpi_ec_t ec = _gcry_ctx_get_pointer (ctx, CONTEXT_TYPE_EC); return _gcry_ecc_set_mpi (name, newvalue, ec); } gpg_err_code_t _gcry_mpi_ec_set_point (const char *name, gcry_mpi_point_t newvalue, gcry_ctx_t ctx) { mpi_ec_t ec = _gcry_ctx_get_pointer (ctx, CONTEXT_TYPE_EC); return _gcry_ecc_set_point (name, newvalue, ec); } /* Given an encoded point in the MPI VALUE and a context EC, decode * the point according to the context and store it in RESULT. On * error an error code is return but RESULT might have been changed. * If no context is given the function tries to decode VALUE by * assuming a 0x04 prefixed uncompressed encoding. */ gpg_err_code_t _gcry_mpi_ec_decode_point (mpi_point_t result, gcry_mpi_t value, mpi_ec_t ec) { gcry_err_code_t rc; if (ec && ec->dialect == ECC_DIALECT_ED25519) rc = _gcry_ecc_eddsa_decodepoint (value, ec, result, NULL, NULL); else if (ec && ec->model == MPI_EC_MONTGOMERY) rc = _gcry_ecc_mont_decodepoint (value, ec, result); else rc = _gcry_ecc_os2ec (result, value); return rc; } /* Compute the affine coordinates from the projective coordinates in POINT. Set them into X and Y. If one coordinate is not required, X or Y may be passed as NULL. CTX is the usual context. Returns: 0 on success or !0 if POINT is at infinity. */ int _gcry_mpi_ec_get_affine (gcry_mpi_t x, gcry_mpi_t y, mpi_point_t point, mpi_ec_t ctx) { if (!mpi_cmp_ui (point->z, 0)) return -1; switch (ctx->model) { case MPI_EC_WEIERSTRASS: /* Using Jacobian coordinates. */ { gcry_mpi_t z1, z2, z3; z1 = mpi_new (0); z2 = mpi_new (0); ec_invm (z1, point->z, ctx); /* z1 = z^(-1) mod p */ ec_mulm (z2, z1, z1, ctx); /* z2 = z^(-2) mod p */ if (x) ec_mulm (x, point->x, z2, ctx); if (y) { z3 = mpi_new (0); ec_mulm (z3, z2, z1, ctx); /* z3 = z^(-3) mod p */ ec_mulm (y, point->y, z3, ctx); mpi_free (z3); } mpi_free (z2); mpi_free (z1); } return 0; case MPI_EC_MONTGOMERY: { if (x) mpi_set (x, point->x); if (y) { log_fatal ("%s: Getting Y-coordinate on %s is not supported\n", "_gcry_mpi_ec_get_affine", "Montgomery"); return -1; } } return 0; case MPI_EC_EDWARDS: { gcry_mpi_t z; z = mpi_new (0); ec_invm (z, point->z, ctx); if (x) ec_mulm (x, point->x, z, ctx); if (y) ec_mulm (y, point->y, z, ctx); _gcry_mpi_release (z); } return 0; default: return -1; } } /* RESULT = 2 * POINT (Weierstrass version). */ static void dup_point_weierstrass (mpi_point_t result, mpi_point_t point, mpi_ec_t ctx) { #define x3 (result->x) #define y3 (result->y) #define z3 (result->z) #define t1 (ctx->t.scratch[0]) #define t2 (ctx->t.scratch[1]) #define t3 (ctx->t.scratch[2]) #define l1 (ctx->t.scratch[3]) #define l2 (ctx->t.scratch[4]) #define l3 (ctx->t.scratch[5]) if (!mpi_cmp_ui (point->y, 0) || !mpi_cmp_ui (point->z, 0)) { /* P_y == 0 || P_z == 0 => [1:1:0] */ mpi_set_ui (x3, 1); mpi_set_ui (y3, 1); mpi_set_ui (z3, 0); } else { if (ec_get_a_is_pminus3 (ctx)) /* Use the faster case. */ { /* L1 = 3(X - Z^2)(X + Z^2) */ /* T1: used for Z^2. */ /* T2: used for the right term. */ ec_pow2 (t1, point->z, ctx); ec_subm (l1, point->x, t1, ctx); ec_mulm (l1, l1, mpi_const (MPI_C_THREE), ctx); ec_addm (t2, point->x, t1, ctx); ec_mulm (l1, l1, t2, ctx); } else /* Standard case. */ { /* L1 = 3X^2 + aZ^4 */ /* T1: used for aZ^4. */ ec_pow2 (l1, point->x, ctx); ec_mulm (l1, l1, mpi_const (MPI_C_THREE), ctx); ec_powm (t1, point->z, mpi_const (MPI_C_FOUR), ctx); ec_mulm (t1, t1, ctx->a, ctx); ec_addm (l1, l1, t1, ctx); } /* Z3 = 2YZ */ ec_mulm (z3, point->y, point->z, ctx); ec_mul2 (z3, z3, ctx); /* L2 = 4XY^2 */ /* T2: used for Y2; required later. */ ec_pow2 (t2, point->y, ctx); ec_mulm (l2, t2, point->x, ctx); ec_mulm (l2, l2, mpi_const (MPI_C_FOUR), ctx); /* X3 = L1^2 - 2L2 */ /* T1: used for L2^2. */ ec_pow2 (x3, l1, ctx); ec_mul2 (t1, l2, ctx); ec_subm (x3, x3, t1, ctx); /* L3 = 8Y^4 */ /* T2: taken from above. */ ec_pow2 (t2, t2, ctx); ec_mulm (l3, t2, mpi_const (MPI_C_EIGHT), ctx); /* Y3 = L1(L2 - X3) - L3 */ ec_subm (y3, l2, x3, ctx); ec_mulm (y3, y3, l1, ctx); ec_subm (y3, y3, l3, ctx); } #undef x3 #undef y3 #undef z3 #undef t1 #undef t2 #undef t3 #undef l1 #undef l2 #undef l3 } /* RESULT = 2 * POINT (Montgomery version). */ static void dup_point_montgomery (mpi_point_t result, mpi_point_t point, mpi_ec_t ctx) { (void)result; (void)point; (void)ctx; log_fatal ("%s: %s not yet supported\n", "_gcry_mpi_ec_dup_point", "Montgomery"); } /* RESULT = 2 * POINT (Twisted Edwards version). */ static void dup_point_edwards (mpi_point_t result, mpi_point_t point, mpi_ec_t ctx) { #define X1 (point->x) #define Y1 (point->y) #define Z1 (point->z) #define X3 (result->x) #define Y3 (result->y) #define Z3 (result->z) #define B (ctx->t.scratch[0]) #define C (ctx->t.scratch[1]) #define D (ctx->t.scratch[2]) #define E (ctx->t.scratch[3]) #define F (ctx->t.scratch[4]) #define H (ctx->t.scratch[5]) #define J (ctx->t.scratch[6]) /* Compute: (X_3 : Y_3 : Z_3) = 2( X_1 : Y_1 : Z_1 ) */ /* B = (X_1 + Y_1)^2 */ ec_addm (B, X1, Y1, ctx); ec_pow2 (B, B, ctx); /* C = X_1^2 */ /* D = Y_1^2 */ ec_pow2 (C, X1, ctx); ec_pow2 (D, Y1, ctx); /* E = aC */ if (ctx->dialect == ECC_DIALECT_ED25519) mpi_sub (E, ctx->p, C); else ec_mulm (E, ctx->a, C, ctx); /* F = E + D */ ec_addm (F, E, D, ctx); /* H = Z_1^2 */ ec_pow2 (H, Z1, ctx); /* J = F - 2H */ ec_mul2 (J, H, ctx); ec_subm (J, F, J, ctx); /* X_3 = (B - C - D) · J */ ec_subm (X3, B, C, ctx); ec_subm (X3, X3, D, ctx); ec_mulm (X3, X3, J, ctx); /* Y_3 = F · (E - D) */ ec_subm (Y3, E, D, ctx); ec_mulm (Y3, Y3, F, ctx); /* Z_3 = F · J */ ec_mulm (Z3, F, J, ctx); #undef X1 #undef Y1 #undef Z1 #undef X3 #undef Y3 #undef Z3 #undef B #undef C #undef D #undef E #undef F #undef H #undef J } /* RESULT = 2 * POINT */ void _gcry_mpi_ec_dup_point (mpi_point_t result, mpi_point_t point, mpi_ec_t ctx) { switch (ctx->model) { case MPI_EC_WEIERSTRASS: dup_point_weierstrass (result, point, ctx); break; case MPI_EC_MONTGOMERY: dup_point_montgomery (result, point, ctx); break; case MPI_EC_EDWARDS: dup_point_edwards (result, point, ctx); break; } } /* RESULT = P1 + P2 (Weierstrass version).*/ static void add_points_weierstrass (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { #define x1 (p1->x ) #define y1 (p1->y ) #define z1 (p1->z ) #define x2 (p2->x ) #define y2 (p2->y ) #define z2 (p2->z ) #define x3 (result->x) #define y3 (result->y) #define z3 (result->z) #define l1 (ctx->t.scratch[0]) #define l2 (ctx->t.scratch[1]) #define l3 (ctx->t.scratch[2]) #define l4 (ctx->t.scratch[3]) #define l5 (ctx->t.scratch[4]) #define l6 (ctx->t.scratch[5]) #define l7 (ctx->t.scratch[6]) #define l8 (ctx->t.scratch[7]) #define l9 (ctx->t.scratch[8]) #define t1 (ctx->t.scratch[9]) #define t2 (ctx->t.scratch[10]) if ( (!mpi_cmp (x1, x2)) && (!mpi_cmp (y1, y2)) && (!mpi_cmp (z1, z2)) ) { /* Same point; need to call the duplicate function. */ _gcry_mpi_ec_dup_point (result, p1, ctx); } else if (!mpi_cmp_ui (z1, 0)) { /* P1 is at infinity. */ mpi_set (x3, p2->x); mpi_set (y3, p2->y); mpi_set (z3, p2->z); } else if (!mpi_cmp_ui (z2, 0)) { /* P2 is at infinity. */ mpi_set (x3, p1->x); mpi_set (y3, p1->y); mpi_set (z3, p1->z); } else { int z1_is_one = !mpi_cmp_ui (z1, 1); int z2_is_one = !mpi_cmp_ui (z2, 1); /* l1 = x1 z2^2 */ /* l2 = x2 z1^2 */ if (z2_is_one) mpi_set (l1, x1); else { ec_pow2 (l1, z2, ctx); ec_mulm (l1, l1, x1, ctx); } if (z1_is_one) mpi_set (l2, x2); else { ec_pow2 (l2, z1, ctx); ec_mulm (l2, l2, x2, ctx); } /* l3 = l1 - l2 */ ec_subm (l3, l1, l2, ctx); /* l4 = y1 z2^3 */ ec_powm (l4, z2, mpi_const (MPI_C_THREE), ctx); ec_mulm (l4, l4, y1, ctx); /* l5 = y2 z1^3 */ ec_powm (l5, z1, mpi_const (MPI_C_THREE), ctx); ec_mulm (l5, l5, y2, ctx); /* l6 = l4 - l5 */ ec_subm (l6, l4, l5, ctx); if (!mpi_cmp_ui (l3, 0)) { if (!mpi_cmp_ui (l6, 0)) { /* P1 and P2 are the same - use duplicate function. */ _gcry_mpi_ec_dup_point (result, p1, ctx); } else { /* P1 is the inverse of P2. */ mpi_set_ui (x3, 1); mpi_set_ui (y3, 1); mpi_set_ui (z3, 0); } } else { /* l7 = l1 + l2 */ ec_addm (l7, l1, l2, ctx); /* l8 = l4 + l5 */ ec_addm (l8, l4, l5, ctx); /* z3 = z1 z2 l3 */ ec_mulm (z3, z1, z2, ctx); ec_mulm (z3, z3, l3, ctx); /* x3 = l6^2 - l7 l3^2 */ ec_pow2 (t1, l6, ctx); ec_pow2 (t2, l3, ctx); ec_mulm (t2, t2, l7, ctx); ec_subm (x3, t1, t2, ctx); /* l9 = l7 l3^2 - 2 x3 */ ec_mul2 (t1, x3, ctx); ec_subm (l9, t2, t1, ctx); /* y3 = (l9 l6 - l8 l3^3)/2 */ ec_mulm (l9, l9, l6, ctx); ec_powm (t1, l3, mpi_const (MPI_C_THREE), ctx); /* fixme: Use saved value*/ ec_mulm (t1, t1, l8, ctx); ec_subm (y3, l9, t1, ctx); ec_mulm (y3, y3, ec_get_two_inv_p (ctx), ctx); } } #undef x1 #undef y1 #undef z1 #undef x2 #undef y2 #undef z2 #undef x3 #undef y3 #undef z3 #undef l1 #undef l2 #undef l3 #undef l4 #undef l5 #undef l6 #undef l7 #undef l8 #undef l9 #undef t1 #undef t2 } /* RESULT = P1 + P2 (Montgomery version).*/ static void add_points_montgomery (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { (void)result; (void)p1; (void)p2; (void)ctx; log_fatal ("%s: %s not yet supported\n", "_gcry_mpi_ec_add_points", "Montgomery"); } /* RESULT = P1 + P2 (Twisted Edwards version).*/ static void add_points_edwards (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { #define X1 (p1->x) #define Y1 (p1->y) #define Z1 (p1->z) #define X2 (p2->x) #define Y2 (p2->y) #define Z2 (p2->z) #define X3 (result->x) #define Y3 (result->y) #define Z3 (result->z) #define A (ctx->t.scratch[0]) #define B (ctx->t.scratch[1]) #define C (ctx->t.scratch[2]) #define D (ctx->t.scratch[3]) #define E (ctx->t.scratch[4]) #define F (ctx->t.scratch[5]) #define G (ctx->t.scratch[6]) #define tmp (ctx->t.scratch[7]) /* Compute: (X_3 : Y_3 : Z_3) = (X_1 : Y_1 : Z_1) + (X_2 : Y_2 : Z_3) */ /* A = Z1 · Z2 */ ec_mulm (A, Z1, Z2, ctx); /* B = A^2 */ ec_pow2 (B, A, ctx); /* C = X1 · X2 */ ec_mulm (C, X1, X2, ctx); /* D = Y1 · Y2 */ ec_mulm (D, Y1, Y2, ctx); /* E = d · C · D */ ec_mulm (E, ctx->b, C, ctx); ec_mulm (E, E, D, ctx); /* F = B - E */ ec_subm (F, B, E, ctx); /* G = B + E */ ec_addm (G, B, E, ctx); /* X_3 = A · F · ((X_1 + Y_1) · (X_2 + Y_2) - C - D) */ ec_addm (tmp, X1, Y1, ctx); ec_addm (X3, X2, Y2, ctx); ec_mulm (X3, X3, tmp, ctx); ec_subm (X3, X3, C, ctx); ec_subm (X3, X3, D, ctx); ec_mulm (X3, X3, F, ctx); ec_mulm (X3, X3, A, ctx); /* Y_3 = A · G · (D - aC) */ if (ctx->dialect == ECC_DIALECT_ED25519) { ec_addm (Y3, D, C, ctx); } else { ec_mulm (Y3, ctx->a, C, ctx); ec_subm (Y3, D, Y3, ctx); } ec_mulm (Y3, Y3, G, ctx); ec_mulm (Y3, Y3, A, ctx); /* Z_3 = F · G */ ec_mulm (Z3, F, G, ctx); #undef X1 #undef Y1 #undef Z1 #undef X2 #undef Y2 #undef Z2 #undef X3 #undef Y3 #undef Z3 #undef A #undef B #undef C #undef D #undef E #undef F #undef G #undef tmp } /* Compute a step of Montgomery Ladder (only use X and Z in the point). Inputs: P1, P2, and x-coordinate of DIF = P1 - P1. Outputs: PRD = 2 * P1 and SUM = P1 + P2. */ static void montgomery_ladder (mpi_point_t prd, mpi_point_t sum, mpi_point_t p1, mpi_point_t p2, gcry_mpi_t dif_x, mpi_ec_t ctx) { ec_addm (sum->x, p2->x, p2->z, ctx); ec_subm (p2->z, p2->x, p2->z, ctx); ec_addm (prd->x, p1->x, p1->z, ctx); ec_subm (p1->z, p1->x, p1->z, ctx); ec_mulm (p2->x, p1->z, sum->x, ctx); ec_mulm (p2->z, prd->x, p2->z, ctx); ec_pow2 (p1->x, prd->x, ctx); ec_pow2 (p1->z, p1->z, ctx); ec_addm (sum->x, p2->x, p2->z, ctx); ec_subm (p2->z, p2->x, p2->z, ctx); ec_mulm (prd->x, p1->x, p1->z, ctx); ec_subm (p1->z, p1->x, p1->z, ctx); ec_pow2 (sum->x, sum->x, ctx); ec_pow2 (sum->z, p2->z, ctx); ec_mulm (prd->z, p1->z, ctx->a, ctx); /* CTX->A: (a-2)/4 */ ec_mulm (sum->z, sum->z, dif_x, ctx); ec_addm (prd->z, p1->x, prd->z, ctx); ec_mulm (prd->z, prd->z, p1->z, ctx); } /* RESULT = P1 + P2 */ void _gcry_mpi_ec_add_points (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { switch (ctx->model) { case MPI_EC_WEIERSTRASS: add_points_weierstrass (result, p1, p2, ctx); break; case MPI_EC_MONTGOMERY: add_points_montgomery (result, p1, p2, ctx); break; case MPI_EC_EDWARDS: add_points_edwards (result, p1, p2, ctx); break; } } /* RESULT = P1 - P2 (Weierstrass version).*/ static void sub_points_weierstrass (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { (void)result; (void)p1; (void)p2; (void)ctx; log_fatal ("%s: %s not yet supported\n", "_gcry_mpi_ec_sub_points", "Weierstrass"); } /* RESULT = P1 - P2 (Montgomery version).*/ static void sub_points_montgomery (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { (void)result; (void)p1; (void)p2; (void)ctx; log_fatal ("%s: %s not yet supported\n", "_gcry_mpi_ec_sub_points", "Montgomery"); } /* RESULT = P1 - P2 (Twisted Edwards version).*/ static void sub_points_edwards (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { mpi_point_t p2i = _gcry_mpi_point_new (0); point_set (p2i, p2); mpi_sub (p2i->x, ctx->p, p2i->x); add_points_edwards (result, p1, p2i, ctx); _gcry_mpi_point_release (p2i); } /* RESULT = P1 - P2 */ void _gcry_mpi_ec_sub_points (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { switch (ctx->model) { case MPI_EC_WEIERSTRASS: sub_points_weierstrass (result, p1, p2, ctx); break; case MPI_EC_MONTGOMERY: sub_points_montgomery (result, p1, p2, ctx); break; case MPI_EC_EDWARDS: sub_points_edwards (result, p1, p2, ctx); break; } } /* Scalar point multiplication - the main function for ECC. If takes an integer SCALAR and a POINT as well as the usual context CTX. RESULT will be set to the resulting point. */ void _gcry_mpi_ec_mul_point (mpi_point_t result, gcry_mpi_t scalar, mpi_point_t point, mpi_ec_t ctx) { gcry_mpi_t x1, y1, z1, k, h, yy; unsigned int i, loops; mpi_point_struct p1, p2, p1inv; if (ctx->model == MPI_EC_EDWARDS || (ctx->model == MPI_EC_WEIERSTRASS && mpi_is_secure (scalar))) { /* Simple left to right binary method. Algorithm 3.27 from * {author={Hankerson, Darrel and Menezes, Alfred J. and Vanstone, Scott}, * title = {Guide to Elliptic Curve Cryptography}, * year = {2003}, isbn = {038795273X}, * url = {http://www.cacr.math.uwaterloo.ca/ecc/}, * publisher = {Springer-Verlag New York, Inc.}} */ unsigned int nbits; int j; nbits = mpi_get_nbits (scalar); if (ctx->model == MPI_EC_WEIERSTRASS) { mpi_set_ui (result->x, 1); mpi_set_ui (result->y, 1); mpi_set_ui (result->z, 0); } else { mpi_set_ui (result->x, 0); mpi_set_ui (result->y, 1); mpi_set_ui (result->z, 1); } if (mpi_is_secure (scalar)) { /* If SCALAR is in secure memory we assume that it is the secret key we use constant time operation. */ mpi_point_struct tmppnt; point_init (&tmppnt); point_resize (result, ctx); point_resize (&tmppnt, ctx); for (j=nbits-1; j >= 0; j--) { _gcry_mpi_ec_dup_point (result, result, ctx); _gcry_mpi_ec_add_points (&tmppnt, result, point, ctx); point_swap_cond (result, &tmppnt, mpi_test_bit (scalar, j), ctx); } point_free (&tmppnt); } else { for (j=nbits-1; j >= 0; j--) { _gcry_mpi_ec_dup_point (result, result, ctx); if (mpi_test_bit (scalar, j)) _gcry_mpi_ec_add_points (result, result, point, ctx); } } return; } else if (ctx->model == MPI_EC_MONTGOMERY) { unsigned int nbits; int j; mpi_point_struct p1_, p2_; mpi_point_t q1, q2, prd, sum; unsigned long sw; /* Compute scalar point multiplication with Montgomery Ladder. Note that we don't use Y-coordinate in the points at all. RESULT->Y will be filled by zero. */ nbits = mpi_get_nbits (scalar); point_init (&p1); point_init (&p2); point_init (&p1_); point_init (&p2_); mpi_set_ui (p1.x, 1); mpi_free (p2.x); p2.x = mpi_copy (point->x); mpi_set_ui (p2.z, 1); point_resize (&p1, ctx); point_resize (&p2, ctx); point_resize (&p1_, ctx); point_resize (&p2_, ctx); q1 = &p1; q2 = &p2; prd = &p1_; sum = &p2_; for (j=nbits-1; j >= 0; j--) { mpi_point_t t; sw = mpi_test_bit (scalar, j); point_swap_cond (q1, q2, sw, ctx); montgomery_ladder (prd, sum, q1, q2, point->x, ctx); point_swap_cond (prd, sum, sw, ctx); t = q1; q1 = prd; prd = t; t = q2; q2 = sum; sum = t; } mpi_clear (result->y); sw = (nbits & 1); point_swap_cond (&p1, &p1_, sw, ctx); if (p1.z->nlimbs == 0) { mpi_set_ui (result->x, 1); mpi_set_ui (result->z, 0); } else { z1 = mpi_new (0); ec_invm (z1, p1.z, ctx); ec_mulm (result->x, p1.x, z1, ctx); mpi_set_ui (result->z, 1); mpi_free (z1); } point_free (&p1); point_free (&p2); point_free (&p1_); point_free (&p2_); return; } x1 = mpi_alloc_like (ctx->p); y1 = mpi_alloc_like (ctx->p); h = mpi_alloc_like (ctx->p); k = mpi_copy (scalar); yy = mpi_copy (point->y); if ( mpi_has_sign (k) ) { k->sign = 0; ec_invm (yy, yy, ctx); } if (!mpi_cmp_ui (point->z, 1)) { mpi_set (x1, point->x); mpi_set (y1, yy); } else { gcry_mpi_t z2, z3; z2 = mpi_alloc_like (ctx->p); z3 = mpi_alloc_like (ctx->p); ec_mulm (z2, point->z, point->z, ctx); ec_mulm (z3, point->z, z2, ctx); ec_invm (z2, z2, ctx); ec_mulm (x1, point->x, z2, ctx); ec_invm (z3, z3, ctx); ec_mulm (y1, yy, z3, ctx); mpi_free (z2); mpi_free (z3); } z1 = mpi_copy (mpi_const (MPI_C_ONE)); mpi_mul (h, k, mpi_const (MPI_C_THREE)); /* h = 3k */ loops = mpi_get_nbits (h); if (loops < 2) { /* If SCALAR is zero, the above mpi_mul sets H to zero and thus LOOPs will be zero. To avoid an underflow of I in the main loop we set LOOP to 2 and the result to (0,0,0). */ loops = 2; mpi_clear (result->x); mpi_clear (result->y); mpi_clear (result->z); } else { mpi_set (result->x, point->x); mpi_set (result->y, yy); mpi_set (result->z, point->z); } mpi_free (yy); yy = NULL; p1.x = x1; x1 = NULL; p1.y = y1; y1 = NULL; p1.z = z1; z1 = NULL; point_init (&p2); point_init (&p1inv); /* Invert point: y = p - y mod p */ point_set (&p1inv, &p1); ec_subm (p1inv.y, ctx->p, p1inv.y, ctx); for (i=loops-2; i > 0; i--) { _gcry_mpi_ec_dup_point (result, result, ctx); if (mpi_test_bit (h, i) == 1 && mpi_test_bit (k, i) == 0) { point_set (&p2, result); _gcry_mpi_ec_add_points (result, &p2, &p1, ctx); } if (mpi_test_bit (h, i) == 0 && mpi_test_bit (k, i) == 1) { point_set (&p2, result); _gcry_mpi_ec_add_points (result, &p2, &p1inv, ctx); } } point_free (&p1); point_free (&p2); point_free (&p1inv); mpi_free (h); mpi_free (k); } /* Return true if POINT is on the curve described by CTX. */ int _gcry_mpi_ec_curve_point (gcry_mpi_point_t point, mpi_ec_t ctx) { int res = 0; gcry_mpi_t x, y, w; x = mpi_new (0); y = mpi_new (0); w = mpi_new (0); switch (ctx->model) { case MPI_EC_WEIERSTRASS: { gcry_mpi_t xxx; if (_gcry_mpi_ec_get_affine (x, y, point, ctx)) goto leave; xxx = mpi_new (0); /* y^2 == x^3 + a·x + b */ ec_pow2 (y, y, ctx); ec_pow3 (xxx, x, ctx); ec_mulm (w, ctx->a, x, ctx); ec_addm (w, w, ctx->b, ctx); ec_addm (w, w, xxx, ctx); if (!mpi_cmp (y, w)) res = 1; _gcry_mpi_release (xxx); } break; case MPI_EC_MONTGOMERY: { #define xx y /* With Montgomery curve, only X-coordinate is valid. */ if (_gcry_mpi_ec_get_affine (x, NULL, point, ctx)) goto leave; /* The equation is: b * y^2 == x^3 + a · x^2 + x */ /* We check if right hand is quadratic residue or not by Euler's criterion. */ /* CTX->A has (a-2)/4 and CTX->B has b^-1 */ ec_mulm (w, ctx->a, mpi_const (MPI_C_FOUR), ctx); ec_addm (w, w, mpi_const (MPI_C_TWO), ctx); ec_mulm (w, w, x, ctx); ec_pow2 (xx, x, ctx); ec_addm (w, w, xx, ctx); ec_addm (w, w, mpi_const (MPI_C_ONE), ctx); ec_mulm (w, w, x, ctx); ec_mulm (w, w, ctx->b, ctx); #undef xx /* Compute Euler's criterion: w^(p-1)/2 */ #define p_minus1 y ec_subm (p_minus1, ctx->p, mpi_const (MPI_C_ONE), ctx); mpi_rshift (p_minus1, p_minus1, 1); ec_powm (w, w, p_minus1, ctx); res = !mpi_cmp_ui (w, 1); #undef p_minus1 } break; case MPI_EC_EDWARDS: { if (_gcry_mpi_ec_get_affine (x, y, point, ctx)) goto leave; /* a · x^2 + y^2 - 1 - b · x^2 · y^2 == 0 */ ec_pow2 (x, x, ctx); ec_pow2 (y, y, ctx); if (ctx->dialect == ECC_DIALECT_ED25519) mpi_sub (w, ctx->p, x); else ec_mulm (w, ctx->a, x, ctx); ec_addm (w, w, y, ctx); ec_subm (w, w, mpi_const (MPI_C_ONE), ctx); ec_mulm (x, x, y, ctx); ec_mulm (x, x, ctx->b, ctx); ec_subm (w, w, x, ctx); if (!mpi_cmp_ui (w, 0)) res = 1; } break; } leave: _gcry_mpi_release (w); _gcry_mpi_release (x); _gcry_mpi_release (y); return res; } + + +int +_gcry_mpi_ec_bad_point (gcry_mpi_point_t point, mpi_ec_t ctx) +{ + int i; + gcry_mpi_t x_bad; + + for (i = 0; (x_bad = ctx->t.scratch[i]); i++) + if (!mpi_cmp (point->x, x_bad)) + return 1; + + return 0; +} diff --git a/src/mpi.h b/src/mpi.h index b5385b5d..aeba7f8b 100644 --- a/src/mpi.h +++ b/src/mpi.h @@ -1,319 +1,320 @@ /* mpi.h - Multi Precision Integers * Copyright (C) 1994, 1996, 1998, * 2001, 2002, 2003, 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 * * Note: This code is heavily based on the GNU MP Library. * Actually it's the same code with only minor changes in the * way the data is stored; this is to support the abstraction * of an optional secure memory allocation which may be used * to avoid revealing of sensitive data due to paging etc. */ #ifndef G10_MPI_H #define G10_MPI_H #include #include #include #include "types.h" #include "../mpi/mpi-asm-defs.h" #include "g10lib.h" #ifndef _GCRYPT_IN_LIBGCRYPT #error this file should only be used inside libgcrypt #endif #ifndef BITS_PER_MPI_LIMB #if BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_INT typedef unsigned int mpi_limb_t; typedef signed int mpi_limb_signed_t; #elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_LONG typedef unsigned long int mpi_limb_t; typedef signed long int mpi_limb_signed_t; #elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_LONG_LONG typedef unsigned long long int mpi_limb_t; typedef signed long long int mpi_limb_signed_t; #elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_SHORT typedef unsigned short int mpi_limb_t; typedef signed short int mpi_limb_signed_t; #else #error BYTES_PER_MPI_LIMB does not match any C type #endif #define BITS_PER_MPI_LIMB (8*BYTES_PER_MPI_LIMB) #endif /*BITS_PER_MPI_LIMB*/ #define DBG_MPI _gcry_get_debug_flag( 2 ); struct gcry_mpi { int alloced; /* Array size (# of allocated limbs). */ int nlimbs; /* Number of valid limbs. */ int sign; /* Indicates a negative number and is also used for opaque MPIs to store the length. */ unsigned int flags; /* Bit 0: Array to be allocated in secure memory space.*/ /* Bit 2: The limb is a pointer to some m_alloced data.*/ /* Bit 4: Immutable MPI - the MPI may not be modified. */ /* Bit 5: Constant MPI - the MPI will not be freed. */ mpi_limb_t *d; /* Array with the limbs */ }; #define MPI_NULL NULL #define mpi_get_nlimbs(a) ((a)->nlimbs) #define mpi_has_sign(a) ((a)->sign) /*-- mpiutil.c --*/ #ifdef M_DEBUG # define mpi_alloc(n) _gcry_mpi_debug_alloc((n), M_DBGINFO( __LINE__ ) ) # define mpi_alloc_secure(n) _gcry_mpi_debug_alloc_secure((n), M_DBGINFO( __LINE__ ) ) # define mpi_free(a) _gcry_mpi_debug_free((a), M_DBGINFO(__LINE__) ) # define mpi_resize(a,b) _gcry_mpi_debug_resize((a),(b), M_DBGINFO(__LINE__) ) # define mpi_copy(a) _gcry_mpi_debug_copy((a), M_DBGINFO(__LINE__) ) gcry_mpi_t _gcry_mpi_debug_alloc( unsigned nlimbs, const char *info ); gcry_mpi_t _gcry_mpi_debug_alloc_secure( unsigned nlimbs, const char *info ); void _gcry_mpi_debug_free( gcry_mpi_t a, const char *info ); void _gcry_mpi_debug_resize( gcry_mpi_t a, unsigned nlimbs, const char *info ); gcry_mpi_t _gcry_mpi_debug_copy( gcry_mpi_t a, const char *info ); #else # define mpi_alloc(n) _gcry_mpi_alloc((n) ) # define mpi_alloc_secure(n) _gcry_mpi_alloc_secure((n) ) # define mpi_free(a) _gcry_mpi_free((a) ) # define mpi_resize(a,b) _gcry_mpi_resize((a),(b)) # define mpi_copy(a) _gcry_mpi_copy((a)) gcry_mpi_t _gcry_mpi_alloc( unsigned nlimbs ); gcry_mpi_t _gcry_mpi_alloc_secure( unsigned nlimbs ); void _gcry_mpi_free( gcry_mpi_t a ); void _gcry_mpi_resize( gcry_mpi_t a, unsigned nlimbs ); gcry_mpi_t _gcry_mpi_copy( gcry_mpi_t a ); #endif void _gcry_mpi_immutable_failed (void); #define mpi_immutable_failed() _gcry_mpi_immutable_failed () #define mpi_is_const(a) ((a)->flags&32) #define mpi_is_immutable(a) ((a)->flags&16) #define mpi_is_opaque(a) ((a) && ((a)->flags&4)) #define mpi_is_secure(a) ((a) && ((a)->flags&1)) #define mpi_clear(a) _gcry_mpi_clear ((a)) #define mpi_alloc_like(a) _gcry_mpi_alloc_like((a)) #define mpi_alloc_set_ui(a) _gcry_mpi_alloc_set_ui ((a)) #define mpi_m_check(a) _gcry_mpi_m_check ((a)) #define mpi_const(n) _gcry_mpi_const ((n)) #define mpi_swap_cond(a,b,sw) _gcry_mpi_swap_cond ((a),(b),(sw)) #define mpi_set_cond(w,u,set) _gcry_mpi_set_cond ((w),(u),(set)) void _gcry_mpi_clear( gcry_mpi_t a ); gcry_mpi_t _gcry_mpi_set_cond (gcry_mpi_t w, const gcry_mpi_t u, unsigned long swap); gcry_mpi_t _gcry_mpi_alloc_like( gcry_mpi_t a ); gcry_mpi_t _gcry_mpi_alloc_set_ui( unsigned long u); void _gcry_mpi_m_check( gcry_mpi_t a ); void _gcry_mpi_swap( gcry_mpi_t a, gcry_mpi_t b); void _gcry_mpi_swap_cond (gcry_mpi_t a, gcry_mpi_t b, unsigned long swap); gcry_mpi_t _gcry_mpi_new (unsigned int nbits); gcry_mpi_t _gcry_mpi_snew (unsigned int nbits); gcry_mpi_t _gcry_mpi_set_opaque_copy (gcry_mpi_t a, const void *p, unsigned int nbits); void *_gcry_mpi_get_opaque_copy (gcry_mpi_t a, unsigned int *nbits); int _gcry_mpi_is_neg (gcry_mpi_t a); void _gcry_mpi_neg (gcry_mpi_t w, gcry_mpi_t u); void _gcry_mpi_abs (gcry_mpi_t w); /* Constants used to return constant MPIs. See _gcry_mpi_init if you want to add more constants. */ #define MPI_NUMBER_OF_CONSTANTS 6 enum gcry_mpi_constants { MPI_C_ZERO, MPI_C_ONE, MPI_C_TWO, MPI_C_THREE, MPI_C_FOUR, MPI_C_EIGHT }; gcry_mpi_t _gcry_mpi_const (enum gcry_mpi_constants no); /*-- mpicoder.c --*/ void _gcry_log_mpidump( const char *text, gcry_mpi_t a ); u32 _gcry_mpi_get_keyid( gcry_mpi_t a, u32 *keyid ); byte *_gcry_mpi_get_buffer (gcry_mpi_t a, unsigned int fill_le, unsigned int *r_nbytes, int *sign); byte *_gcry_mpi_get_buffer_extra (gcry_mpi_t a, unsigned int fill_le, int extraalloc, unsigned int *r_nbytes, int *sign); byte *_gcry_mpi_get_secure_buffer (gcry_mpi_t a, unsigned int fill_le, unsigned *r_nbytes, int *sign); void _gcry_mpi_set_buffer ( gcry_mpi_t a, const void *buffer, unsigned int nbytes, int sign ); gpg_err_code_t _gcry_mpi_to_octet_string (unsigned char **r_frame, void *space, gcry_mpi_t value, size_t nbytes); /*-- mpi-div.c --*/ #define mpi_fdiv_r_ui(a,b,c) _gcry_mpi_fdiv_r_ui((a),(b),(c)) #define mpi_fdiv_r(a,b,c) _gcry_mpi_fdiv_r((a),(b),(c)) #define mpi_fdiv_q(a,b,c) _gcry_mpi_fdiv_q((a),(b),(c)) #define mpi_fdiv_qr(a,b,c,d) _gcry_mpi_fdiv_qr((a),(b),(c),(d)) #define mpi_tdiv_r(a,b,c) _gcry_mpi_tdiv_r((a),(b),(c)) #define mpi_tdiv_qr(a,b,c,d) _gcry_mpi_tdiv_qr((a),(b),(c),(d)) #define mpi_tdiv_q_2exp(a,b,c) _gcry_mpi_tdiv_q_2exp((a),(b),(c)) #define mpi_divisible_ui(a,b) _gcry_mpi_divisible_ui((a),(b)) ulong _gcry_mpi_fdiv_r_ui( gcry_mpi_t rem, gcry_mpi_t dividend, ulong divisor ); void _gcry_mpi_fdiv_r( gcry_mpi_t rem, gcry_mpi_t dividend, gcry_mpi_t divisor ); void _gcry_mpi_fdiv_q( gcry_mpi_t quot, gcry_mpi_t dividend, gcry_mpi_t divisor ); void _gcry_mpi_fdiv_qr( gcry_mpi_t quot, gcry_mpi_t rem, gcry_mpi_t dividend, gcry_mpi_t divisor ); void _gcry_mpi_tdiv_r( gcry_mpi_t rem, gcry_mpi_t num, gcry_mpi_t den); void _gcry_mpi_tdiv_qr( gcry_mpi_t quot, gcry_mpi_t rem, gcry_mpi_t num, gcry_mpi_t den); void _gcry_mpi_tdiv_q_2exp( gcry_mpi_t w, gcry_mpi_t u, unsigned count ); int _gcry_mpi_divisible_ui(gcry_mpi_t dividend, ulong divisor ); /*-- mpi-mod.c --*/ #define mpi_barrett_init(m,f) _gcry_mpi_barrett_init ((m),(f)) #define mpi_barrett_free(c) _gcry_mpi_barrett_free ((c)) #define mpi_mod_barrett(r,a,c) _gcry_mpi_mod_barrett ((r), (a), (c)) #define mpi_mul_barrett(r,u,v,c) _gcry_mpi_mul_barrett ((r), (u), (v), (c)) /* Context used with Barrett reduction. */ struct barrett_ctx_s; typedef struct barrett_ctx_s *mpi_barrett_t; mpi_barrett_t _gcry_mpi_barrett_init (gcry_mpi_t m, int copy); void _gcry_mpi_barrett_free (mpi_barrett_t ctx); void _gcry_mpi_mod_barrett (gcry_mpi_t r, gcry_mpi_t x, mpi_barrett_t ctx); void _gcry_mpi_mul_barrett (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, mpi_barrett_t ctx); /*-- mpi-mpow.c --*/ #define mpi_mulpowm(a,b,c,d) _gcry_mpi_mulpowm ((a),(b),(c),(d)) void _gcry_mpi_mulpowm( gcry_mpi_t res, gcry_mpi_t *basearray, gcry_mpi_t *exparray, gcry_mpi_t mod); /*-- mpi-scan.c --*/ #define mpi_trailing_zeros(a) _gcry_mpi_trailing_zeros ((a)) int _gcry_mpi_getbyte( gcry_mpi_t a, unsigned idx ); void _gcry_mpi_putbyte( gcry_mpi_t a, unsigned idx, int value ); unsigned _gcry_mpi_trailing_zeros( gcry_mpi_t a ); /*-- mpi-bit.c --*/ #define mpi_normalize(a) _gcry_mpi_normalize ((a)) void _gcry_mpi_normalize( gcry_mpi_t a ); /*-- ec.c --*/ /* Object to represent a point in projective coordinates. */ struct gcry_mpi_point { gcry_mpi_t x; gcry_mpi_t y; gcry_mpi_t z; }; typedef struct gcry_mpi_point mpi_point_struct; typedef struct gcry_mpi_point *mpi_point_t; void _gcry_mpi_point_init (mpi_point_t p); void _gcry_mpi_point_free_parts (mpi_point_t p); void _gcry_mpi_get_point (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, mpi_point_t point); void _gcry_mpi_snatch_point (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, mpi_point_t point); /* Models describing an elliptic curve. */ enum gcry_mpi_ec_models { /* The Short Weierstrass equation is y^2 = x^3 + ax + b */ MPI_EC_WEIERSTRASS = 0, /* The Montgomery equation is by^2 = x^3 + ax^2 + x */ MPI_EC_MONTGOMERY, /* The Twisted Edwards equation is ax^2 + y^2 = 1 + bx^2y^2 Note that we use 'b' instead of the commonly used 'd'. */ MPI_EC_EDWARDS }; /* Dialects used with elliptic curves. It is easier to keep the definition here than in ecc-common.h. */ enum ecc_dialects { ECC_DIALECT_STANDARD = 0, ECC_DIALECT_ED25519 }; void _gcry_mpi_point_log (const char *name, mpi_point_t point, mpi_ec_t ctx); #define log_printpnt(a,p,c) _gcry_mpi_point_log ((a), (p), (c)) mpi_ec_t _gcry_mpi_ec_p_internal_new (enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b); gpg_err_code_t _gcry_mpi_ec_p_new (gcry_ctx_t *r_ctx, enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b); void _gcry_mpi_ec_free (mpi_ec_t ctx); void _gcry_mpi_ec_dup_point (mpi_point_t result, mpi_point_t point, mpi_ec_t ctx); void _gcry_mpi_ec_add_points (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx); void _gcry_mpi_ec_sub_points (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx); void _gcry_mpi_ec_mul_point (mpi_point_t result, gcry_mpi_t scalar, mpi_point_t point, mpi_ec_t ctx); int _gcry_mpi_ec_curve_point (gcry_mpi_point_t point, mpi_ec_t ctx); +int _gcry_mpi_ec_bad_point (gcry_mpi_point_t point, mpi_ec_t ctx); gcry_mpi_t _gcry_mpi_ec_ec2os (gcry_mpi_point_t point, mpi_ec_t ectx); gcry_mpi_t _gcry_mpi_ec_get_mpi (const char *name, gcry_ctx_t ctx, int copy); gcry_mpi_point_t _gcry_mpi_ec_get_point (const char *name, gcry_ctx_t ctx, int copy); gpg_err_code_t _gcry_mpi_ec_set_mpi (const char *name, gcry_mpi_t newvalue, gcry_ctx_t ctx); gpg_err_code_t _gcry_mpi_ec_set_point (const char *name, gcry_mpi_point_t newvalue, gcry_ctx_t ctx); gpg_err_code_t _gcry_mpi_ec_decode_point (mpi_point_t result, gcry_mpi_t value, mpi_ec_t ec); /*-- ecc-curves.c --*/ gpg_err_code_t _gcry_mpi_ec_new (gcry_ctx_t *r_ctx, gcry_sexp_t keyparam, const char *curvename); #endif /*G10_MPI_H*/