From de9f953b9f3b32f94bb8ea1769bfd2e86f9b83ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Fri, 23 Oct 2015 15:50:37 +0200 Subject: [PATCH] Optimize more common cases in ecp_muladd() --- library/ecp.c | 43 +++++++++++++++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/library/ecp.c b/library/ecp.c index 4abc87c61..19bb4882e 100644 --- a/library/ecp.c +++ b/library/ecp.c @@ -1683,8 +1683,39 @@ cleanup: } #endif /* ECP_SHORTWEIERSTRASS */ +/* + * R = m * P with shortcuts for m == 1 and m == -1 + * NOT constant-time - ONLY for short Weierstrass! + */ +static int mbedtls_ecp_mul_shortcuts( mbedtls_ecp_group *grp, + mbedtls_ecp_point *R, + const mbedtls_mpi *m, + const mbedtls_ecp_point *P ) +{ + int ret; + + if( mbedtls_mpi_cmp_int( m, 1 ) == 0 ) + { + MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) ); + } + else if( mbedtls_mpi_cmp_int( m, -1 ) == 0 ) + { + MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) ); + if( mbedtls_mpi_cmp_int( &R->Y, 0 ) != 0 ) + MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &R->Y, &grp->P, &R->Y ) ); + } + else + { + MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, m, P, NULL, NULL ) ); + } + +cleanup: + return( ret ); +} + /* * Linear combination + * NOT constant-time */ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, @@ -1698,16 +1729,8 @@ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, mbedtls_ecp_point_init( &mP ); - /* Optimize some simple special cases */ - if( mbedtls_mpi_cmp_int( m, 1 ) == 0 ) - MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &mP, P ) ); - else - MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, &mP, m, P, NULL, NULL ) ); - - if( mbedtls_mpi_cmp_int( n, 1 ) == 0 ) - MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, Q ) ); - else - MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, n, Q, NULL, NULL ) ); + MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, &mP, m, P ) ); + MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, R, n, Q ) ); MBEDTLS_MPI_CHK( ecp_add_mixed( grp, R, &mP, R ) ); MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, R ) );