Unify mbedtls_mpi_add_mpi and mbedtls_mpi_sub_mpi

mbedtls_mpi_add_mpi() and mbedtls_mpi_sub_mpi() have the same logic, just
with one bit to flip in the sign calculation. Move the shared logic to a new
auxiliary function. This slightly reduces the code size (if the compiler
doesn't inline) and reduces the maintenance burden.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
This commit is contained in:
Gilles Peskine 2022-11-09 21:34:09 +01:00
parent 32605b24be
commit 72ee1e3f3c

View File

@ -972,10 +972,12 @@ cleanup:
return( ret );
}
/*
* Signed addition: X = A + B
/* Common function for signed addition and subtraction.
* Calculate A + B * flip_B where flip_B is 1 or -1.
*/
int mbedtls_mpi_add_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
static int add_sub_mpi( mbedtls_mpi *X,
const mbedtls_mpi *A, const mbedtls_mpi *B,
int flip_B )
{
int ret, s;
MPI_VALIDATE_RET( X != NULL );
@ -983,7 +985,7 @@ int mbedtls_mpi_add_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi
MPI_VALIDATE_RET( B != NULL );
s = A->s;
if( A->s * B->s < 0 )
if( A->s * B->s * flip_B < 0 )
{
if( mbedtls_mpi_cmp_abs( A, B ) >= 0 )
{
@ -1007,39 +1009,20 @@ cleanup:
return( ret );
}
/*
* Signed addition: X = A + B
*/
int mbedtls_mpi_add_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
{
return( add_sub_mpi( X, A, B, 1 ) );
}
/*
* Signed subtraction: X = A - B
*/
int mbedtls_mpi_sub_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
{
int ret, s;
MPI_VALIDATE_RET( X != NULL );
MPI_VALIDATE_RET( A != NULL );
MPI_VALIDATE_RET( B != NULL );
s = A->s;
if( A->s * B->s > 0 )
{
if( mbedtls_mpi_cmp_abs( A, B ) >= 0 )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, A, B ) );
X->s = s;
}
else
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, B, A ) );
X->s = -s;
}
}
else
{
MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( X, A, B ) );
X->s = s;
}
cleanup:
return( ret );
return( add_sub_mpi( X, A, B, -1 ) );
}
/*