MPI random: add unit tests with a previously nonzero value

Add unit tests for mbedtls_mpi_fill_random() and mbedtls_mpi_random()
when the resulting MPI object previously had a nonzero value. I wrote
those to catch a bug that I introduced during the development of
mbedtls_mpi_random() (but does not appear in a committed version).

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
This commit is contained in:
Gilles Peskine 2021-04-02 00:02:27 +02:00
parent 1a7df4eda0
commit 422e867acb
2 changed files with 86 additions and 25 deletions

View file

@ -1400,13 +1400,23 @@ exit:
/* END_CASE */
/* BEGIN_CASE */
void mpi_fill_random( int wanted_bytes, int rng_bytes, int expected_ret )
void mpi_fill_random( int wanted_bytes, int rng_bytes,
int before, int expected_ret )
{
mbedtls_mpi X;
int ret;
size_t bytes_left = rng_bytes;
mbedtls_mpi_init( &X );
if( before != 0 )
{
/* Set X to sign(before) * 2^(|before|-1) */
TEST_ASSERT( mbedtls_mpi_lset( &X, before > 0 ? 1 : -1 ) == 0 );
if( before < 0 )
before = - before;
TEST_ASSERT( mbedtls_mpi_shift_l( &X, before - 1 ) == 0 );
}
ret = mbedtls_mpi_fill_random( &X, wanted_bytes,
f_rng_bytes_left, &bytes_left );
TEST_ASSERT( ret == expected_ret );
@ -1538,7 +1548,7 @@ exit:
/* END_CASE */
/* BEGIN_CASE */
void mpi_random_grown( int min, data_t *bound_bytes, int nlimbs )
void mpi_random_sizes( int min, data_t *bound_bytes, int nlimbs, int before )
{
mbedtls_mpi upper_bound;
mbedtls_mpi result;
@ -1546,6 +1556,15 @@ void mpi_random_grown( int min, data_t *bound_bytes, int nlimbs )
mbedtls_mpi_init( &upper_bound );
mbedtls_mpi_init( &result );
if( before != 0 )
{
/* Set result to sign(before) * 2^(|before|-1) */
TEST_ASSERT( mbedtls_mpi_lset( &result, before > 0 ? 1 : -1 ) == 0 );
if( before < 0 )
before = - before;
TEST_ASSERT( mbedtls_mpi_shift_l( &result, before - 1 ) == 0 );
}
TEST_EQUAL( 0, mbedtls_mpi_grow( &result, nlimbs ) );
TEST_EQUAL( 0, mbedtls_mpi_read_binary( &upper_bound,
bound_bytes->x, bound_bytes->len ) );