From b3e3d79e1a2524b2d66d8c3c251ca099f2ce7abe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Fri, 26 Jun 2020 11:03:19 +0200 Subject: [PATCH] RSA: remove redundant GCD call in prepare_blinding() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit inv_mod() already returns a specific error code if the value is not invertible, so no need to check in advance that it is. Also, this is a preparation for blinding the call to inv_mod(), which is made easier by avoiding the redundancy (otherwise the call to gcd() would need to be blinded too). Signed-off-by: Manuel Pégourié-Gonnard --- library/rsa.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/library/rsa.c b/library/rsa.c index 6c457468e..00b379c2b 100644 --- a/library/rsa.c +++ b/library/rsa.c @@ -800,11 +800,14 @@ static int rsa_prepare_blinding( mbedtls_rsa_context *ctx, return( MBEDTLS_ERR_RSA_RNG_FAILED ); MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vf, ctx->len - 1, f_rng, p_rng ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &ctx->Vi, &ctx->Vf, &ctx->N ) ); - } while( mbedtls_mpi_cmp_int( &ctx->Vi, 1 ) != 0 ); + + ret = mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vf, &ctx->N ); + if( ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) + goto cleanup; + + } while( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) /* Blinding value: Vi = Vf^(-e) mod N */ - MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vf, &ctx->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN ) );