From eadf31d56a3e59fb28d70fc00675648283984a5d Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Wed, 24 Mar 2021 12:46:46 +0100 Subject: [PATCH] mbedtls_ecp_gen_privkey_mx: simplify the size calculation logic mbedtls_ecp_gen_privkey_mx generates a random number with a certain top bit set. Depending on the size, it would either generate a number with that top bit being random, then forcibly set the top bit to 1 (when high_bit is not a multiple of 8); or generate a number with that top bit being 0, then set the top bit to 1 (when high_bit is a multiple of 8). Change it to always generate the top bit randomly first. This doesn't make any difference in practice: the probability distribution is the same either way, and no supported or plausible curve has a size of the form 8n+1 anyway. But it slightly simplifies reasoning about the behavior of this function. Signed-off-by: Gilles Peskine --- library/ecp.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/library/ecp.c b/library/ecp.c index fb841dfe9..983a67fd0 100644 --- a/library/ecp.c +++ b/library/ecp.c @@ -3048,13 +3048,16 @@ int mbedtls_ecp_gen_privkey_mx( size_t high_bit, void *p_rng ) { int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; - size_t n_bytes = ( high_bit + 7 ) / 8; + size_t n_random_bytes = high_bit / 8 + 1; /* [Curve25519] page 5 */ - MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_bytes, f_rng, p_rng ) ); + /* Generate a (high_bit+1)-bit random number by generating just enough + * random bytes, then shifting out extra bits from the top (necessary + * when (high_bit+1) is not a multiple of 8). */ + MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_random_bytes, + f_rng, p_rng ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_random_bytes - high_bit - 1 ) ); - /* Make sure the most significant bit is exactly at high_bit */ - MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_bytes - high_bit - 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, high_bit, 1 ) ); /* Make sure the last two bits are unset for Curve448, three bits for