From 0c9bbb0ff8938453d0fa9b78d11812a81859580f Mon Sep 17 00:00:00 2001 From: Darryl Green Date: Tue, 2 Oct 2018 13:21:35 +0100 Subject: [PATCH] Fix bias in random number generation in Miller-Rabin test When a random number is generated for the Miller-Rabin primality test, if the bit length of the random number is larger than the number being tested, the random number is shifted right to have the same bit length. This introduces bias, as the random number is now guaranteed to be larger than 2^(bit length-1). Changing this to instead zero all bits higher than the tested numbers bit length will remove this bias and keep the random number being uniformly generated. --- library/bignum.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/bignum.c b/library/bignum.c index af523fcd3..1c3bfe0e5 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -2077,7 +2077,7 @@ static int mpi_miller_rabin( const mbedtls_mpi *X, size_t rounds, j = mbedtls_mpi_bitlen( &A ); k = mbedtls_mpi_bitlen( &W ); if (j > k) { - MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &A, j - k ) ); + A.p[A.n - 1] &= ( (mbedtls_mpi_uint) 1 << ( k - ( A.n - 1 ) * biL - 1 ) ) - 1; } if (count++ > 30) {