mbedtls_ecp_gen_privkey_mx: make bit manipulations unconditional

Don't calculate the bit-size of the initially generated random number.
This is not necessary to reach the desired distribution of private
keys, and creates a (tiny) side channel opportunity.

This changes the way the result is derived from the random number, but
does not affect the resulting distribution.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/library/ecp.c b/library/ecp.c
index 1592e87..81ba933 100644
--- a/library/ecp.c
+++ b/library/ecp.c
@@ -3065,18 +3065,14 @@
                                 void *p_rng )
 {
     int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
-    size_t b;
     size_t n_bytes = ( high_bit + 7 ) / 8;
 
     /* [Curve25519] page 5 */
     MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_bytes, f_rng, p_rng ) );
 
-    /* Make sure the most significant bit is high_bit */
-    b = mbedtls_mpi_bitlen( d ); /* mbedtls_mpi_bitlen is one-based */
-    if( b > high_bit + 1 )
-        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - 1 - high_bit ) );
-    else
-        MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 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
        Curve25519 */