From e3f95ed25b36b592298f26c8117002a5a1c352d1 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 9dc4e4d4f..ae5e7cfa0 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -2090,7 +2090,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) {