diff --git a/ChangeLog b/ChangeLog index 8c0dbb134..2af6cf246 100644 --- a/ChangeLog +++ b/ChangeLog @@ -63,6 +63,8 @@ Changes Alex Hixon. * Allow configuring the shared library extension by setting the DLEXT environment variable when using the project makefiles. + * Optimize unnecessary zeroing in mbedtls_mpi_copy. Based on a contribution + by Alexey Skalozub in #405. = mbed TLS 2.8.0 branch released 2018-03-16 diff --git a/include/mbedtls/bignum.h b/include/mbedtls/bignum.h index 3bf02a7ee..31383b1eb 100644 --- a/include/mbedtls/bignum.h +++ b/include/mbedtls/bignum.h @@ -204,6 +204,8 @@ void mbedtls_mpi_free( mbedtls_mpi *X ); /** * \brief Enlarge to the specified number of limbs * + * This function does nothing if the MPI is already large enough. + * * \param X MPI to grow * \param nblimbs The target number of limbs * @@ -215,19 +217,23 @@ int mbedtls_mpi_grow( mbedtls_mpi *X, size_t nblimbs ); /** * \brief Resize down, keeping at least the specified number of limbs * + * If \c X is smaller than \c nblimbs, it is resized up + * instead. + * * \param X MPI to shrink * \param nblimbs The minimum number of limbs to keep * * \return 0 if successful, * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * (this can only happen when resizing up). */ int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs ); /** * \brief Copy the contents of Y into X * - * \param X Destination MPI - * \param Y Source MPI + * \param X Destination MPI. It is enlarged if necessary. + * \param Y Source MPI. * * \return 0 if successful, * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed diff --git a/library/bignum.c b/library/bignum.c index ff72d30d0..47bf1ef97 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -184,7 +184,7 @@ int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs ) */ int mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y ) { - int ret; + int ret = 0; size_t i; if( X == Y ) @@ -203,9 +203,15 @@ int mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y ) X->s = Y->s; - MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i ) ); + if( X->n < i ) + { + MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i ) ); + } + else + { + memset( X->p + i, 0, ( X->n - i ) * ciL ); + } - memset( X->p, 0, X->n * ciL ); memcpy( X->p, Y->p, i * ciL ); cleanup: