Fix odd bitlength RSA key generation
Fix issue that caused a hang up when generating RSA keys of odd
bitlength.
diff --git a/ChangeLog b/ChangeLog
index 017d6a2..38a13e0 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -9,6 +9,7 @@
* Fix issue in Makefile that prevented building using armar. #386
* Fix bug in mbedtls_x509_crt_parse that caused trailing extra data in the
buffer after DER certificates to be included in the raw representation.
+ * Fix issue that caused a hang up when generating RSA keys of odd bitlength
Changes
* On ARM platforms, when compiling with -O0 with GCC, Clang or armcc5,
diff --git a/library/rsa.c b/library/rsa.c
index efdd055..a95a6b1 100644
--- a/library/rsa.c
+++ b/library/rsa.c
@@ -96,7 +96,8 @@
if( f_rng == NULL || nbits < 128 || exponent < 3 )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
- mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 ); mbedtls_mpi_init( &H ); mbedtls_mpi_init( &G );
+ mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 );
+ mbedtls_mpi_init( &H ); mbedtls_mpi_init( &G );
/*
* find primes P and Q with Q < P so that:
@@ -106,14 +107,15 @@
do
{
- MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, ( nbits + 1 ) >> 1, 0,
+ MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1, 0,
f_rng, p_rng ) );
- MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, ( nbits + 1 ) >> 1, 0,
+ if( nbits % 2 )
+ MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, ( nbits >> 1 ) + 1, 0,
f_rng, p_rng ) );
-
- if( mbedtls_mpi_cmp_mpi( &ctx->P, &ctx->Q ) < 0 )
- mbedtls_mpi_swap( &ctx->P, &ctx->Q );
+ else
+ MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, 0,
+ f_rng, p_rng ) );
if( mbedtls_mpi_cmp_mpi( &ctx->P, &ctx->Q ) == 0 )
continue;