Merge remote-tracking branch 'upstream-public/pr/1268' into mbedtls-1.3
diff --git a/ChangeLog b/ChangeLog
index b3bab77..854e86c 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -45,6 +45,9 @@
      MilenkoMitrovic, #1104
    * Fix mbedtls_timing_alarm(0) on Unix.
    * Fix use of uninitialized memory in mbedtls_timing_get_timer when reset=1.
+   * Fix issue in RSA key generation program programs/x509/rsa_genkey
+     where the failure of CTR DRBG initialization lead to freeing an
+     RSA context without proper initialization beforehand.
 
 Changes
    * Extend cert_write example program by options to set the CRT version
diff --git a/programs/pkey/rsa_genkey.c b/programs/pkey/rsa_genkey.c
index 0270b53..305158b 100644
--- a/programs/pkey/rsa_genkey.c
+++ b/programs/pkey/rsa_genkey.c
@@ -74,6 +74,7 @@
     fflush( stdout );
 
     entropy_init( &entropy );
+    rsa_init( &rsa, RSA_PKCS_V15, 0 );
     if( ( ret = ctr_drbg_init( &ctr_drbg, entropy_func, &entropy,
                                (const unsigned char *) pers,
                                strlen( pers ) ) ) != 0 )
@@ -85,7 +86,6 @@
     polarssl_printf( " ok\n  . Generating the RSA key [ %d-bit ]...", KEY_SIZE );
     fflush( stdout );
 
-    rsa_init( &rsa, RSA_PKCS_V15, 0 );
 
     if( ( ret = rsa_gen_key( &rsa, ctr_drbg_random, &ctr_drbg, KEY_SIZE,
                              EXPONENT ) ) != 0 )
diff --git a/tests/suites/test_suite_mpi.function b/tests/suites/test_suite_mpi.function
index c0fdf8e..ad2b32e 100644
--- a/tests/suites/test_suite_mpi.function
+++ b/tests/suites/test_suite_mpi.function
@@ -823,7 +823,8 @@
         TEST_ASSERT( mpi_is_prime( &X, rnd_std_rand, NULL ) == 0 );
         if( safe )
         {
-            mpi_shift_r( &X, 1 ); /* X = ( X - 1 ) / 2 */
+            /* X = ( X - 1 ) / 2 */
+            TEST_ASSERT( mpi_shift_r( &X, 1 ) == 0 );
             TEST_ASSERT( mpi_is_prime( &X, rnd_std_rand, NULL ) == 0 );
         }
     }