Check that 1 < D, E < N in `mbedtls_rsa_validate_params`
diff --git a/include/mbedtls/rsa.h b/include/mbedtls/rsa.h
index df0ade8..46daac5 100644
--- a/include/mbedtls/rsa.h
+++ b/include/mbedtls/rsa.h
@@ -174,12 +174,13 @@
* \param p_rng PRNG context for f_rng, or NULL
*
* \return
- * - 0 if the following conditions are satisfied:
- * - N = PQ if N,P,Q != NULL
+ * - 0 if the following conditions are satisfied
+ * if all relevant parameters are provided:
+ * - P prime if f_rng != NULL
+ * - Q prime if f_rng != NULL
+ * - 1 < N = PQ
+ * - 1 < D, E < N
* - D and E are modular inverses modulo P-1 and Q-1
- * if D,E,P,Q != NULL
- * - P prime if f_rng, P != NULL
- * - Q prime if f_rng, Q != NULL
* - A non-zero error code otherwise.
*
* \note The function can be used with a restricted set of arguments
diff --git a/library/rsa.c b/library/rsa.c
index 841f489..b0ba1eb 100644
--- a/library/rsa.c
+++ b/library/rsa.c
@@ -422,13 +422,13 @@
#endif /* MBEDTLS_GENPRIME */
/*
- * Step 2: Check that N = PQ
+ * Step 2: Check that 1 < N = PQ
*/
if( P != NULL && Q != NULL && N != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, P, Q ) );
- if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 ||
+ if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( &K, N ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
@@ -437,15 +437,29 @@
}
/*
- * Step 3: Check that D, E are inverse modulo P-1 and Q-1
+ * Step 3: Check and 1 < D, E < N if present.
+ */
+
+ if( N != NULL && D != NULL && E != NULL )
+ {
+ if ( mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||
+ mbedtls_mpi_cmp_int( E, 1 ) <= 0 ||
+ mbedtls_mpi_cmp_mpi( D, N ) >= 0 ||
+ mbedtls_mpi_cmp_mpi( E, N ) >= 0 )
+ {
+ ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
+ goto cleanup;
+ }
+ }
+
+ /*
+ * Step 4: Check that D, E are inverse modulo P-1 and Q-1
*/
if( P != NULL && Q != NULL && D != NULL && E != NULL )
{
if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 ||
- mbedtls_mpi_cmp_int( Q, 1 ) <= 0 ||
- mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||
- mbedtls_mpi_cmp_int( E, 1 ) <= 0 )
+ mbedtls_mpi_cmp_int( Q, 1 ) <= 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;