mbedtls_ecp_gen_privkey_mx: remove the exception for all-zero
The library rejected an RNG input of all-bits-zero, which led to the
key 2^{254} (for Curve25519) having a 31/32 chance of being generated
compared to other keys. This had no practical impact because the
probability of non-compliance was 2^{-256}, but needlessly
complicated the code.
The exception was added in 98e28a74e33f32bcb855e16f8d5d2016b2102129 to
avoid the case where b - 1 wraps because b is 0. Instead, change the
comparison code to avoid calculating b - 1.
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/library/ecp.c b/library/ecp.c
index 94f3c4a..6c4b334 100644
--- a/library/ecp.c
+++ b/library/ecp.c
@@ -3052,14 +3052,12 @@
size_t n_bytes = ( high_bit + 7 ) / 8;
/* [Curve25519] page 5 */
- do {
- MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_bytes, f_rng, p_rng ) );
- } while( mbedtls_mpi_bitlen( d ) == 0);
+ 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 ) - 1; /* position of the highest bit in d */
- if( b > high_bit )
- MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - 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 ) );