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.
This commit is contained in:
Darryl Green 2018-10-02 13:21:35 +01:00
parent e0e7ddf99e
commit e3f95ed25b

View File

@ -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) {