Restore P>Q in RSA key generation (#558)

The PKCS#1 standard says nothing about the relation between P and Q
but many libraries guarantee P>Q and mbed TLS did so too in earlier
versions.

This commit restores this behaviour.
This commit is contained in:
Janos Follath 2016-09-21 13:18:12 +01:00 committed by Simon Butcher
parent 2c73577d4a
commit 3072458ec3
4 changed files with 14 additions and 12 deletions

View File

@ -19,6 +19,7 @@ Bugfix
by inestlerode. #559.
* Fix documentation and implementation missmatch for function arguments of
mbedtls_gcm_finish(). Found by cmiatpaar. #602
* Guarantee that P>Q at RSA key generation. #558
= mbed TLS 1.3.17 branch 2016-06-28

View File

@ -97,6 +97,9 @@ int rsa_gen_key( rsa_context *ctx,
if( f_rng == NULL || nbits < 128 || exponent < 3 )
return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
if( nbits % 2 )
return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
mpi_init( &P1 ); mpi_init( &Q1 );
mpi_init( &H ); mpi_init( &G );
@ -111,16 +114,8 @@ int rsa_gen_key( rsa_context *ctx,
MPI_CHK( mpi_gen_prime( &ctx->P, nbits >> 1, 0,
f_rng, p_rng ) );
if( nbits % 2 )
{
MPI_CHK( mpi_gen_prime( &ctx->Q, ( nbits >> 1 ) + 1, 0,
f_rng, p_rng ) );
}
else
{
MPI_CHK( mpi_gen_prime( &ctx->Q, nbits >> 1, 0,
f_rng, p_rng ) );
}
if( mpi_cmp_mpi( &ctx->P, &ctx->Q ) == 0 )
continue;
@ -129,6 +124,9 @@ int rsa_gen_key( rsa_context *ctx,
if( mpi_msb( &ctx->N ) != nbits )
continue;
if( mpi_cmp_mpi( &ctx->P, &ctx->Q ) < 0 )
mpi_swap( &ctx->P, &ctx->Q );
MPI_CHK( mpi_sub_int( &P1, &ctx->P, 1 ) );
MPI_CHK( mpi_sub_int( &Q1, &ctx->Q, 1 ) );
MPI_CHK( mpi_mul_mpi( &H, &P1, &Q1 ) );

View File

@ -361,7 +361,7 @@ RSA Generate Key - 2048 bit key
rsa_gen_key:2048:3:0
RSA Generate Key - 1025 bit key
rsa_gen_key:1025:3:0
rsa_gen_key:1025:3:POLARSSL_ERR_RSA_BAD_INPUT_DATA
RSA PKCS1 Encrypt Bad RNG
depends_on:POLARSSL_PKCS1_V15

View File

@ -668,14 +668,17 @@ void rsa_gen_key( int nrbits, int exponent, int result)
entropy_init( &entropy );
TEST_ASSERT( ctr_drbg_init( &ctr_drbg, entropy_func, &entropy,
(const unsigned char *) pers, strlen( pers ) ) == 0 );
(const unsigned char *) pers,
strlen( pers ) ) == 0 );
rsa_init( &ctx, 0, 0 );
TEST_ASSERT( rsa_gen_key( &ctx, ctr_drbg_random, &ctr_drbg, nrbits, exponent ) == result );
TEST_ASSERT( rsa_gen_key( &ctx, ctr_drbg_random, &ctr_drbg, nrbits,
exponent ) == result );
if( result == 0 )
{
TEST_ASSERT( rsa_check_privkey( &ctx ) == 0 );
TEST_ASSERT( mpi_cmp_mpi( &ctx.P, &ctx.Q ) > 0 );
}
exit: