From 735d2c99e769148a63964baf796c6f69efa7b624 Mon Sep 17 00:00:00 2001 From: Tom Cosgrove Date: Wed, 3 May 2023 09:50:10 +0100 Subject: [PATCH] Backport 2.28: Use mbedtls_ct_uint_if() rather than mbedtls_ct_cond_select_sign() Signed-off-by: Tom Cosgrove --- library/constant_time.c | 40 +++------------------------------------- 1 file changed, 3 insertions(+), 37 deletions(-) diff --git a/library/constant_time.c b/library/constant_time.c index 527930129b9c..c0f53bbe77f3 100644 --- a/library/constant_time.c +++ b/library/constant_time.c @@ -263,40 +263,6 @@ unsigned mbedtls_ct_uint_if(unsigned condition, #if defined(MBEDTLS_BIGNUM_C) -/** Select between two sign values without branches. - * - * This is functionally equivalent to `condition ? if1 : if0` but uses only bit - * operations in order to avoid branches. - * - * \note if1 and if0 must be either 1 or -1, otherwise the result - * is undefined. - * - * \param condition Condition to test; must be either 0 or 1. - * \param if1 The first sign; must be either +1 or -1. - * \param if0 The second sign; must be either +1 or -1. - * - * \return \c if1 if \p condition is nonzero, otherwise \c if0. - * */ -static int mbedtls_ct_cond_select_sign(unsigned char condition, - int if1, - int if0) -{ - /* In order to avoid questions about what we can reasonably assume about - * the representations of signed integers, move everything to unsigned - * by taking advantage of the fact that if1 and if0 are either +1 or -1. */ - unsigned uif1 = if1 + 1; - unsigned uif0 = if0 + 1; - - /* condition was 0 or 1, mask is 0 or 2 as are uif1 and uif0 */ - const unsigned mask = condition << 1; - - /* select uif1 or uif0 */ - unsigned ur = (uif0 & ~mask) | (uif1 & mask); - - /* ur is now 0 or 2, convert back to -1 or +1 */ - return (int) ur - 1; -} - void mbedtls_ct_mpi_uint_cond_assign(size_t n, mbedtls_mpi_uint *dest, const mbedtls_mpi_uint *src, @@ -559,7 +525,7 @@ int mbedtls_mpi_safe_cond_assign(mbedtls_mpi *X, MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n)); - X->s = mbedtls_ct_cond_select_sign(assign, Y->s, X->s); + X->s = (int) mbedtls_ct_uint_if(assign, Y->s, X->s); mbedtls_ct_mpi_uint_cond_assign(Y->n, X->p, Y->p, assign); @@ -599,8 +565,8 @@ int mbedtls_mpi_safe_cond_swap(mbedtls_mpi *X, MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Y, X->n)); s = X->s; - X->s = mbedtls_ct_cond_select_sign(swap, Y->s, X->s); - Y->s = mbedtls_ct_cond_select_sign(swap, s, Y->s); + X->s = (int) mbedtls_ct_uint_if(swap, Y->s, X->s); + Y->s = (int) mbedtls_ct_uint_if(swap, s, Y->s); for (i = 0; i < X->n; i++) {