Skip to content

Commit 79a1da6

Browse files
Janos Follathmpg
Janos Follath
authored andcommitted
Improved on the previous fix and added a test case to cover both types
of carries.
1 parent a65477d commit 79a1da6

File tree

2 files changed

+10
-18
lines changed

2 files changed

+10
-18
lines changed

library/bignum.c

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -883,22 +883,11 @@ int mbedtls_mpi_add_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi
883883
{
884884
int ret;
885885
size_t i, j;
886-
mbedtls_mpi_uint *o, *p, c;
887-
mbedtls_mpi TB;
886+
mbedtls_mpi_uint *o, *p, c, tmp;
888887

889888
if( X == B )
890889
{
891-
B = A; A = X;
892-
893-
if( B == A )
894-
{
895-
// Making a temporary copy instead of shifting by one to deny
896-
// the possibility of corresponding side-channel attacks.
897-
mbedtls_mpi_init( &TB );
898-
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) );
899-
900-
B = &TB;
901-
}
890+
const mbedtls_mpi *T = A; A = X; B = T;
902891
}
903892

904893
if( X != A )
@@ -917,10 +906,14 @@ int mbedtls_mpi_add_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi
917906

918907
o = B->p; p = X->p; c = 0;
919908

909+
/*
910+
* tmp is used because it might happen that p == o
911+
*/
920912
for( i = 0; i < j; i++, o++, p++ )
921913
{
914+
tmp= *o;
922915
*p += c; c = ( *p < c );
923-
*p += *o; c += ( *p < *o );
916+
*p += tmp; c += ( *p < tmp );
924917
}
925918

926919
while( c != 0 )
@@ -935,10 +928,6 @@ int mbedtls_mpi_add_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi
935928
}
936929

937930
cleanup:
938-
if( &TB == B )
939-
{
940-
mbedtls_mpi_free( &TB );
941-
}
942931

943932
return( ret );
944933
}

tests/suites/test_suite_mpi.data

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,9 @@ mbedtls_mpi_add_mpi_inplace:10:"12345678":10:"24691356"
301301
Test mbedtls_mpi_add_mpi inplace #2
302302
mbedtls_mpi_add_mpi_inplace:10:"643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153":10:"1287616013607108878460259709922985398302772215068026865836146879048276529684741260122739430789478268181845874665180769440794266671939098512645241958073373266427807905932350214193538360035292323703146295192780306"
303303

304+
Test mbedtls_mpi_add_mpi inplace #3
305+
mbedtls_mpi_add_mpi_inplace:16:"ffffffffffffffffffffffffffffffff":16:"01fffffffffffffffffffffffffffffffe"
306+
304307
Test mbedtls_mpi_add_int #1
305308
mbedtls_mpi_add_int:10:"2039568783564019774057658669290345772801939933143482630947726464532830627227012776329":9871232:10:"2039568783564019774057658669290345772801939933143482630947726464532830627227022647561"
306309

0 commit comments

Comments
 (0)