From 3b63d09fead5623c42cb3f0e54e36d52604ccfe8 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Wed, 16 Nov 2022 22:06:18 +0100 Subject: [PATCH] Make the main loop's logic clearer The loop ends when there are no more bits to process, with one twist: when that happens, we need to clear the window one last time. Since the window does not start empty (E_limbs==0 is not supported), the loop always starts with a non-empty window and some bits to process. So it's correct to move the window clearing logic to the end of the loop. This lets us exit the loop when the end of the exponent is reached. It would be clearer not to do the final window clearing inside the loop, so we wouldn't need to repeat the loop termination condition (end of exponent reached) inside the loop. However, this requires duplicating the code to clear the window. Empirically, this causes a significant code size increase, even if the window clearing code is placed into a function. Signed-off-by: Gilles Peskine --- library/bignum_core.c | 37 +++++++++++++++---------------------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/library/bignum_core.c b/library/bignum_core.c index c05e603226..737e08df2f 100644 --- a/library/bignum_core.c +++ b/library/bignum_core.c @@ -683,29 +683,8 @@ int mbedtls_mpi_core_exp_mod( mbedtls_mpi_uint *X, mbedtls_mpi_uint window = 0; size_t window_bits = 0; - while( 1 ) + do { - size_t window_bits_missing = wsize - window_bits; - - const int no_more_bits = - ( E_bit_index == 0 ) && ( E_limb_index == 0 ); - const int window_full = - ( window_bits_missing == 0 ); - - /* Clear window if it's full or if we don't have further bits. */ - if( window_full || no_more_bits ) - { - if( window_bits == 0 ) - break; - /* Select table entry, square and multiply */ - mbedtls_mpi_core_ct_uint_table_lookup( Wselect, Wtable, - AN_limbs, welem, window ); - mbedtls_mpi_core_montmul( X, X, Wselect, AN_limbs, N, AN_limbs, mm, temp ); - window = 0; - window_bits = 0; - continue; - } - /* Square */ mbedtls_mpi_core_montmul( X, X, X, AN_limbs, N, AN_limbs, mm, temp ); @@ -722,7 +701,21 @@ int mbedtls_mpi_core_exp_mod( mbedtls_mpi_uint *X, ++window_bits; window <<= 1; window |= ( E[E_limb_index] >> E_bit_index ) & 1; + + /* Clear window if it's full. Also clear the window at the end, + * when we've finished processing the exponent. */ + if( window_bits == wsize || + ( E_bit_index == 0 && E_limb_index == 0 ) ) + { + /* Select table entry, square and multiply */ + mbedtls_mpi_core_ct_uint_table_lookup( Wselect, Wtable, + AN_limbs, welem, window ); + mbedtls_mpi_core_montmul( X, X, Wselect, AN_limbs, N, AN_limbs, mm, temp ); + window = 0; + window_bits = 0; + } } + while( ! ( E_bit_index == 0 && E_limb_index == 0 ) ); /* Convert X back to normal presentation */ const mbedtls_mpi_uint one = 1;