Move calculating RR into a separate function
So far we needed it only locally here, but we will need calculating RR
for safe unblinding in RSA as well.
Signed-off-by: Janos Follath <janos.follath@arm.com>
diff --git a/library/bignum.c b/library/bignum.c
index 3e1c48c..551fd81 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -2039,6 +2039,20 @@
return ret;
}
+int mbedtls_mpi_get_mont_r2_unsafe(mbedtls_mpi *X,
+ const mbedtls_mpi *N)
+{
+ int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+
+ MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, 1));
+ MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(X, N->n * 2 * biL));
+ MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(X, X, N));
+ MBEDTLS_MPI_CHK(mbedtls_mpi_shrink(X, N->n));
+
+cleanup:
+ return ret;
+}
+
/*
* Sliding-window exponentiation: X = A^E mod N (HAC 14.85)
*/
@@ -2153,9 +2167,7 @@
* If 1st call, pre-compute R^2 mod N
*/
if (prec_RR == NULL || prec_RR->p == NULL) {
- MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&RR, 1));
- MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&RR, N->n * 2 * biL));
- MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&RR, &RR, N));
+ mbedtls_mpi_get_mont_r2_unsafe(&RR, N);
if (prec_RR != NULL) {
memcpy(prec_RR, &RR, sizeof(mbedtls_mpi));
diff --git a/library/bignum_internal.h b/library/bignum_internal.h
new file mode 100644
index 0000000..39909f3
--- /dev/null
+++ b/library/bignum_internal.h
@@ -0,0 +1,31 @@
+/**
+ * Low level bignum functions
+ *
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_BIGNUM_INTERNAL_H
+#define MBEDTLS_BIGNUM_INTERNAL_H
+
+#include "mbedtls/bignum.h"
+
+/**
+ * \brief Calculate the square of the Montgomery constant. (Needed
+ * for conversion and operations in Montgomery form.)
+ *
+ * \param[out] X A pointer to the result of the calculation of
+ * the square of the Montgomery constant:
+ * 2^{2*n*biL} mod N.
+ * \param[in] N Little-endian presentation of the modulus, which must be odd.
+ *
+ * \return 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if there is not enough space
+ * to store the value of Montgomery constant squared.
+ * \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p N modulus is zero.
+ * \return #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p N modulus is negative.
+ */
+int mbedtls_mpi_get_mont_r2_unsafe(mbedtls_mpi *X,
+ const mbedtls_mpi *N);
+
+#endif /* MBEDTLS_BIGNUM_INTERNAL_H */