From 6ab924de1de252e306c929339a0e74466854572d 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 96afccb0e..2878505c0 100644 --- a/library/rsa.c +++ b/library/rsa.c @@ -764,11 +764,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 ) );