From 8461c0e2a88120a53e97f8d544755855b2feac6a Mon Sep 17 00:00:00 2001 From: Janos Follath Date: Fri, 11 Oct 2019 10:43:40 +0100 Subject: [PATCH] mbedtls_mpi_cmp_mpi_ct: remove multiplications Multiplication is known to have measurable timing variations based on the operands. For example it typically is much faster if one of the operands is zero. Remove them from constant time code. --- library/bignum.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/library/bignum.c b/library/bignum.c index 06445cc11..f57b328ad 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -946,6 +946,11 @@ static int ct_lt_mpi_uint( const mbedtls_mpi_uint x, const mbedtls_mpi_uint y ) return ret; } +static int ct_bool_get_mask( unsigned int b ) +{ + return ~( b - 1 ); +} + /* * Compare signed values in constant time */ @@ -973,7 +978,7 @@ int mbedtls_mpi_cmp_mpi_ct( const mbedtls_mpi *X, const mbedtls_mpi *Y, sign_X = X->s; sign_Y = Y->s; cond = ( ( sign_X ^ sign_Y ) >> ( sizeof( unsigned int ) * 8 - 1 ) ); - *ret = cond * X->s; + *ret = ct_bool_get_mask( cond ) & X->s; done = cond; for( i = X->n; i > 0; i-- ) @@ -986,8 +991,8 @@ int mbedtls_mpi_cmp_mpi_ct( const mbedtls_mpi *X, const mbedtls_mpi *Y, * } */ cond = ct_lt_mpi_uint( Y->p[i - 1], X->p[i - 1] ); - *ret |= ( cond * ( 1 - done ) ) * X->s; - done |= cond * ( 1 - done ); + *ret |= ct_bool_get_mask( cond & ( 1 - done ) ) & X->s; + done |= cond & ( 1 - done ); /* * if( ( X->p[i - 1] < Y->p[i - 1] ) && !done ) @@ -997,9 +1002,8 @@ int mbedtls_mpi_cmp_mpi_ct( const mbedtls_mpi *X, const mbedtls_mpi *Y, * } */ cond = ct_lt_mpi_uint( X->p[i - 1], Y->p[i - 1] ); - *ret |= ( cond * ( 1 - done ) ) * -X->s; - done |= cond * ( 1 - done ); - + *ret |= ct_bool_get_mask( cond & ( 1 - done ) ) & -X->s; + done |= cond & ( 1 - done ); } return( 0 );