diff --git a/library/bignum_core.c b/library/bignum_core.c index 1a3e0b9b6..ee3d704a1 100644 --- a/library/bignum_core.c +++ b/library/bignum_core.c @@ -449,9 +449,10 @@ mbedtls_mpi_uint mbedtls_mpi_core_sub(mbedtls_mpi_uint *X, mbedtls_mpi_uint c = 0; for (size_t i = 0; i < limbs; i++) { - mbedtls_mpi_uint z = (A[i] < c); + mbedtls_mpi_uint z = mbedtls_ct_mpi_uint_if(mbedtls_ct_uint_lt(A[i], c), + 1, 0); mbedtls_mpi_uint t = A[i] - c; - c = (t < B[i]) + z; + c = mbedtls_ct_mpi_uint_if(mbedtls_ct_uint_lt(t, B[i]), 1, 0) + z; X[i] = t - B[i]; } diff --git a/tests/suites/test_suite_bignum_core.function b/tests/suites/test_suite_bignum_core.function index db84d6238..61eeaf545 100644 --- a/tests/suites/test_suite_bignum_core.function +++ b/tests/suites/test_suite_bignum_core.function @@ -1317,3 +1317,33 @@ exit: mbedtls_free(X); } /* END_CASE */ + +/* BEGIN_CASE */ +void mpi_core_check_sub_ct(char *input_A, char *input_B, int exp_ret) +{ + mbedtls_mpi_uint *A = NULL; + mbedtls_mpi_uint *B = NULL; + mbedtls_mpi_uint *X = NULL; + size_t A_limbs, B_limbs; + int ret; + + TEST_EQUAL(0, mbedtls_test_read_mpi_core(&A, &A_limbs, input_A)); + TEST_EQUAL(0, mbedtls_test_read_mpi_core(&B, &B_limbs, input_B)); + + TEST_EQUAL(A_limbs, B_limbs); + + size_t limbs = A_limbs; + TEST_CALLOC(X, limbs); + + TEST_CF_SECRET(A, A_limbs * sizeof(mbedtls_mpi_uint)); + TEST_CF_SECRET(B, B_limbs * sizeof(mbedtls_mpi_uint)); + + ret = mbedtls_mpi_core_sub(X, A, B, limbs); + TEST_EQUAL(ret, exp_ret); + +exit: + mbedtls_free(A); + mbedtls_free(B); + mbedtls_free(X); +} +/* END_CASE */ diff --git a/tests/suites/test_suite_bignum_core.misc.data b/tests/suites/test_suite_bignum_core.misc.data index ba8602997..ccf375052 100644 --- a/tests/suites/test_suite_bignum_core.misc.data +++ b/tests/suites/test_suite_bignum_core.misc.data @@ -523,3 +523,9 @@ mpi_core_clz:64:0 CLZ: 100000 0: skip overly long input mpi_core_clz:100000:0 + +Constant time Subtraction +mpi_core_check_sub_ct:"1234567890abcdef0":"10000000000000000":0 + +Constant time Subtraction #2 +mpi_core_check_sub_ct:"10000000000000000":"1234567890abcdef0":1