From 66414209519a912dc63d346916b52187982b9e73 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Wed, 21 Sep 2022 15:36:16 +0200 Subject: [PATCH] Bignum core: Break shift_r function out of the classic shift_r This commit contains the function prototype for mbedtls_mpi_core_shift_r, and the implementation minimally modified from mbedtls_mpi_shift_r. Signed-off-by: Gilles Peskine --- library/bignum.c | 35 ++++++++++++++++++++++------------- library/bignum_core.h | 15 +++++++++++++++ 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/library/bignum.c b/library/bignum.c index 1c7f9197f..0787272fe 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -770,27 +770,38 @@ cleanup: * Right-shift: X >>= count */ int mbedtls_mpi_shift_r( mbedtls_mpi *X, size_t count ) +{ + MPI_VALIDATE_RET( X != NULL ); + if( X->n != 0 ) + mbedtls_mpi_core_shift_r( X->p, X->n, count ); + return( 0 ); +} + +void mbedtls_mpi_core_shift_r( mbedtls_mpi_uint *X, size_t limbs, + size_t count ) { size_t i, v0, v1; mbedtls_mpi_uint r0 = 0, r1; - MPI_VALIDATE_RET( X != NULL ); v0 = count / biL; v1 = count & (biL - 1); - if( v0 > X->n || ( v0 == X->n && v1 > 0 ) ) - return mbedtls_mpi_lset( X, 0 ); + if( v0 > limbs || ( v0 == limbs && v1 > 0 ) ) + { + memset( X, 0, limbs * ciL ); + return; + } /* * shift by count / limb_size */ if( v0 > 0 ) { - for( i = 0; i < X->n - v0; i++ ) - X->p[i] = X->p[i + v0]; + for( i = 0; i < limbs - v0; i++ ) + X[i] = X[i + v0]; - for( ; i < X->n; i++ ) - X->p[i] = 0; + for( ; i < limbs; i++ ) + X[i] = 0; } /* @@ -798,16 +809,14 @@ int mbedtls_mpi_shift_r( mbedtls_mpi *X, size_t count ) */ if( v1 > 0 ) { - for( i = X->n; i > 0; i-- ) + for( i = limbs; i > 0; i-- ) { - r1 = X->p[i - 1] << (biL - v1); - X->p[i - 1] >>= v1; - X->p[i - 1] |= r0; + r1 = X[i - 1] << (biL - v1); + X[i - 1] >>= v1; + X[i - 1] |= r0; r0 = r1; } } - - return( 0 ); } /* diff --git a/library/bignum_core.h b/library/bignum_core.h index 196736d05..4ba14331c 100644 --- a/library/bignum_core.h +++ b/library/bignum_core.h @@ -262,6 +262,21 @@ int mbedtls_mpi_core_write_be( const mbedtls_mpi_uint *A, unsigned char *output, size_t output_length ); +/** \brief Shift a machine integer right by a number of bits. + * + * Shifting by more bits than there are bit positions + * in \p X is valid and results in setting \p X to 0. + * + * This function's execution time depends on the value + * of \p count (and of course \p limbs). + * + * \param[in,out] X The number to shift. + * \param limbs The number of limbs of \p X. This must be at least 1. + * \param count The number of bits to shift by. + */ +void mbedtls_mpi_core_shift_r( mbedtls_mpi_uint *X, size_t limbs, + size_t count ); + /** * \brief Conditional addition of two fixed-size large unsigned integers, * returning the carry.