mirror of
https://github.com/Mbed-TLS/mbedtls.git
synced 2025-08-08 17:42:09 +03:00
Add core constant time comparison
Unfortunately reusing the new function from the signed constant time comparison is not trivial. One option would be to do temporary conditional swaps which would prevent qualifying input to const. Another way would be to add an additional flag for the sign and make it an integral part of the computation, which would defeat the purpose of having an unsigned core comparison. Going with two separate function for now and the signed version can be retired/compiled out with the legacy API eventually. The new function in theory could be placed into either `library/constant_time.c` or `library/bignum_new.c`. Going with the first as the other functions in the second are not constant time yet and this distinction seems more valuable for new (as opposed to belonging to the `_core` functions. Signed-off-by: Janos Follath <janos.follath@arm.com>
This commit is contained in:
@@ -741,6 +741,50 @@ cleanup:
|
||||
return( ret );
|
||||
}
|
||||
|
||||
/*
|
||||
* Compare unsigned values in constant time
|
||||
*/
|
||||
unsigned mbedtls_mpi_core_lt_ct( const mbedtls_mpi_uint *X,
|
||||
const mbedtls_mpi_uint *Y,
|
||||
size_t len )
|
||||
{
|
||||
size_t i;
|
||||
/* The value of any of these variables is either 0 or 1 at all times. */
|
||||
unsigned ret, cond, done;
|
||||
|
||||
ret = cond = done = 0;
|
||||
|
||||
for( i = len; i > 0; i-- )
|
||||
{
|
||||
/*
|
||||
* If Y[i - 1] < X[i - 1] then X < Y is false and the result must
|
||||
* remain 0.
|
||||
*
|
||||
* Again even if we can make a decision, we just mark the result and
|
||||
* the fact that we are done and continue looping.
|
||||
*/
|
||||
cond = mbedtls_ct_mpi_uint_lt( Y[i - 1], X[i - 1] );
|
||||
done |= cond;
|
||||
|
||||
/*
|
||||
* If X[i - 1] < Y[i - 1] then X < Y is true.
|
||||
*
|
||||
* Again even if we can make a decision, we just mark the result and
|
||||
* the fact that we are done and continue looping.
|
||||
*/
|
||||
cond = mbedtls_ct_mpi_uint_lt( X[i - 1], Y[i - 1] );
|
||||
ret |= cond & ( 1 - done );
|
||||
done |= cond;
|
||||
}
|
||||
|
||||
/*
|
||||
* If all the limbs were equal, then the numbers are equal, X < Y is false
|
||||
* and leaving the result 0 is correct.
|
||||
*/
|
||||
|
||||
return( ret );
|
||||
}
|
||||
|
||||
/*
|
||||
* Compare signed values in constant time
|
||||
*/
|
||||
|
Reference in New Issue
Block a user