mbedtls_mpi_random: avoid local allocation
Rewrite the minimum bound comparison to avoid a local allocation. This costs
a bit of code size, but saves RAM. This is in preparation for moving the
bulk of the function to the bignum_core module where allocation is not
permitted.
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/library/bignum.c b/library/bignum.c
index a68957a..98d2442 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -1968,10 +1968,9 @@
{
int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
int count;
- unsigned lt_lower = 1, lt_upper = 0;
+ unsigned ge_lower = 1, lt_upper = 0;
size_t n_bits = mbedtls_mpi_bitlen( N );
size_t n_bytes = ( n_bits + 7 ) / 8;
- mbedtls_mpi lower_bound;
if( min < 0 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
@@ -1997,14 +1996,10 @@
*/
count = ( n_bytes > 4 ? 30 : 250 );
- mbedtls_mpi_init( &lower_bound );
-
/* Ensure that target MPI has exactly the same number of limbs
* as the upper bound, even if the upper bound has leading zeros.
* This is necessary for the mbedtls_mpi_lt_mpi_ct() check. */
MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, N->n ) );
- MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &lower_bound, N->n ) );
- MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &lower_bound, min ) );
/*
* Match the procedure given in RFC 6979 §3.3 (deterministic ECDSA)
@@ -2027,13 +2022,12 @@
goto cleanup;
}
- MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, &lower_bound, <_lower ) );
- MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, N, <_upper ) );
+ ge_lower = mbedtls_mpi_core_uint_le_mpi( min, X->p, X->n );
+ lt_upper = mbedtls_mpi_core_lt_ct( X->p, N->p, N->n );
}
- while( lt_lower != 0 || lt_upper == 0 );
+ while( ge_lower == 0 || lt_upper == 0 );
cleanup:
- mbedtls_mpi_free( &lower_bound );
return( ret );
}