From 0727ca41b7418378d6d063b8ade62b7437c98d0a Mon Sep 17 00:00:00 2001 From: Hanno Becker Date: Wed, 25 Oct 2017 16:07:09 +0100 Subject: [PATCH] Make mpi_read_binary time constant This commit modifies mpi_read_binary to always allocate the minimum number of limbs required to hold the entire buffer provided to the function, regardless of its content. Previously, leading zero bytes in the input data were detected and used to reduce memory footprint and time, but this non-constant behavior turned out to be non-tolerable for the cryptographic applications this function is used for. --- library/bignum.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/library/bignum.c b/library/bignum.c index 4829d916b..f5130b406 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -678,16 +678,20 @@ cleanup: int mpi_read_binary( mpi *X, const unsigned char *buf, size_t buflen ) { int ret; - size_t i, j, n; + size_t i, j; + size_t const limbs = CHARS_TO_LIMBS( buflen ); - for( n = 0; n < buflen; n++ ) - if( buf[n] != 0 ) - break; + /* Ensure that target MPI has exactly the necessary number of limbs */ + if( X->n != limbs ) + { + mpi_free( X ); + mpi_init( X ); + MPI_CHK( mpi_grow( X, limbs ) ); + } - MPI_CHK( mpi_grow( X, CHARS_TO_LIMBS( buflen - n ) ) ); MPI_CHK( mpi_lset( X, 0 ) ); - for( i = buflen, j = 0; i > n; i--, j++ ) + for( i = buflen, j = 0; i > 0; i--, j++ ) X->p[j / ciL] |= ((t_uint) buf[i - 1]) << ((j % ciL) << 3); cleanup: