mirror of
https://github.com/Mbed-TLS/mbedtls.git
synced 2026-09-02 16:29:57 +00:00
ecp: take advantage of new modp functions
The old functions only guaranteed an output in the range [-a * P, b * P] for a and b "small enough". The new functions have a stricter contract, allowing the final reduction to be done efficiently in constant time. Signed-off-by: Manuel Pégourié-Gonnard <[email protected]>
This commit is contained in:
@@ -213,11 +213,11 @@ mbedtls_ecp_point;
|
||||
*
|
||||
* If \p modp is NULL, reduction modulo \p P is done using a generic algorithm.
|
||||
* Otherwise, \p modp must point to a function that takes an \p mbedtls_mpi in the
|
||||
* range of <code>0..2^(2*pbits)-1</code>, and transforms it in-place to an integer
|
||||
* which is congruent mod \p P to the given MPI, and is close enough to \p pbits
|
||||
* in size, so that it may be efficiently brought in the 0..P-1 range by a few
|
||||
* additions or subtractions. Therefore, it is only an approximate modular
|
||||
* reduction. It must return 0 on success and non-zero on failure.
|
||||
* range of [0, 2^(2*pbits)), and transforms it in-place to an integer which is
|
||||
* congruent mod \p P to the given MPI, is in the range [0, 2P), and has no more
|
||||
* non-zero limbs than P, so that it may be efficiently brought into the range
|
||||
* [0, P) by a single constant-time conditional subtraction.
|
||||
* It must return 0 on success and non-zero on failure.
|
||||
*
|
||||
* \note Alternative implementations of the ECP module must obey the
|
||||
* following constraints.
|
||||
|
||||
+6
-9
@@ -69,6 +69,7 @@
|
||||
|
||||
#include "bn_mul.h"
|
||||
#include "bignum_internal.h"
|
||||
#include "bignum_core.h"
|
||||
#include "ecp_invasive.h"
|
||||
|
||||
#include <string.h>
|
||||
@@ -1009,15 +1010,11 @@ static int ecp_modp(mbedtls_mpi *N, const mbedtls_ecp_group *grp)
|
||||
|
||||
MBEDTLS_MPI_CHK(grp->modp(N));
|
||||
|
||||
/* N->s < 0 is a much faster test, which fails only if N is 0 */
|
||||
while (N->s < 0 && mbedtls_mpi_cmp_int(N, 0) != 0) {
|
||||
MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(N, N, &grp->P));
|
||||
}
|
||||
|
||||
while (mbedtls_mpi_cmp_mpi(N, &grp->P) >= 0) {
|
||||
/* we known P, N and the result are positive */
|
||||
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(N, N, &grp->P));
|
||||
}
|
||||
/* The previous call left N in the range [0, 2P) with no more limbs than P
|
||||
* (see documentation of mbedtls_ecp_mod_pXXX_raw() in ecp_invasive.h),
|
||||
* so we can bring it into the range [0, P) in constant time. */
|
||||
mbedtls_mpi_uint c = mbedtls_mpi_core_sub(N->p, N->p, grp->P.p, grp->P.n);
|
||||
(void) mbedtls_mpi_core_add_if(N->p, grp->P.p, grp->P.n, (unsigned) c);
|
||||
|
||||
cleanup:
|
||||
return ret;
|
||||
|
||||
Reference in New Issue
Block a user