diff --git a/library/ecp.c b/library/ecp.c index 6c4b33424..fb841dfe9 100644 --- a/library/ecp.c +++ b/library/ecp.c @@ -3048,18 +3048,14 @@ int mbedtls_ecp_gen_privkey_mx( size_t high_bit, 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 */ diff --git a/tests/suites/test_suite_ecp.data b/tests/suites/test_suite_ecp.data index 21a71922e..5f92ca459 100644 --- a/tests/suites/test_suite_ecp.data +++ b/tests/suites/test_suite_ecp.data @@ -277,17 +277,13 @@ depends_on:MBEDTLS_ECP_DP_SECP192R1_ENABLED mbedtls_ecp_gen_key:MBEDTLS_ECP_DP_SECP192R1 ECP generate Montgomery key: Curve25519, random in range -genkey_mx_known_answer:254:"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8" - -ECP generate Montgomery key: Curve25519, set high bit -genkey_mx_known_answer:254:"0f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8" +genkey_mx_known_answer:254:"9e020406080a0c0e10121416181a1c1e20222426282a2c2e30323436383a3df0":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8" ECP generate Montgomery key: Curve25519, clear higher bit -## If the bit 255 is set, the library shifts the random number right. genkey_mx_known_answer:254:"ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8":"7f808101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f78" ECP generate Montgomery key: Curve25519, clear low bits -genkey_mx_known_answer:254:"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1eff":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8" +genkey_mx_known_answer:254:"9e020406080a0c0e10121416181a1c1e20222426282a2c2e30323436383a3dff":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8" ECP generate Montgomery key: Curve25519, random = all-bits-zero genkey_mx_known_answer:254:"0000000000000000000000000000000000000000000000000000000000000000":"4000000000000000000000000000000000000000000000000000000000000000"