From 9e1c532847af26ea6504720c6755b668b4b1d0da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Wed, 13 Aug 2025 14:14:19 +0200 Subject: [PATCH] RSA: use CT gcd-modinv in deduce_private_exponent() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Manuel Pégourié-Gonnard --- library/bignum.c | 6 +++--- library/bignum_internal.h | 20 ++++++++++++++++++++ library/rsa_alt_helpers.c | 6 +++++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/library/bignum.c b/library/bignum.c index 00aa79ca2f..f6b8f99981 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -1963,9 +1963,9 @@ cleanup: * * Return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the inverse doesn't exist. */ -static int mbedtls_mpi_inv_mod_even_in_range(mbedtls_mpi *X, - mbedtls_mpi const *A, - mbedtls_mpi const *N) +int mbedtls_mpi_inv_mod_even_in_range(mbedtls_mpi *X, + mbedtls_mpi const *A, + mbedtls_mpi const *N) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_mpi I, G; diff --git a/library/bignum_internal.h b/library/bignum_internal.h index a947497007..341346222d 100644 --- a/library/bignum_internal.h +++ b/library/bignum_internal.h @@ -98,4 +98,24 @@ int mbedtls_mpi_inv_mod_odd(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N); +/** + * \brief Modular inverse: X = A^-1 mod N with N even, + * A odd and 1 < A < N. + * + * \param[out] X The inverse of \p A modulo \p N on success, + * indeterminate otherwise. + * \param[in] A The number to invert. Must be odd, greated than 1 + * and less than \p N. + * \param[in] N The modulus. Must be even and greater than 1. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if preconditions were not + * met. + * \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if A is not invertible mod N. + */ +int mbedtls_mpi_inv_mod_even_in_range(mbedtls_mpi *X, + mbedtls_mpi const *A, + mbedtls_mpi const *N); + #endif /* bignum_internal.h */ diff --git a/library/rsa_alt_helpers.c b/library/rsa_alt_helpers.c index 08adbe3eb8..50a5c4e0d7 100644 --- a/library/rsa_alt_helpers.c +++ b/library/rsa_alt_helpers.c @@ -198,6 +198,10 @@ int mbedtls_rsa_deduce_private_exponent(mbedtls_mpi const *P, return MBEDTLS_ERR_MPI_BAD_INPUT_DATA; } + if (mbedtls_mpi_get_bit(E, 0) != 1) { + return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE; + } + mbedtls_mpi_init(&K); mbedtls_mpi_init(&L); @@ -216,7 +220,7 @@ int mbedtls_rsa_deduce_private_exponent(mbedtls_mpi const *P, * This is FIPS 186-4 §B.3.1 criterion 3(b). * This will return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if E is not coprime to * (P-1)(Q-1), also validating FIPS 186-4 §B.3.1 criterion 2(a). */ - MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(D, E, &K)); + MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod_even_in_range(D, E, &K)); cleanup: