Skip to content

Commit

Permalink
Merge pull request #7545 from tom-cosgrove-arm/use-mbedtls_ct_uint_if…
Browse files Browse the repository at this point in the history
…-rather-than-mbedtls_ct_cond_select_sign-2.28

Backport 2.28: Use mbedtls_ct_uint_if() rather than mbedtls_ct_cond_select_sign()
  • Loading branch information
daverodgman authored May 4, 2023
2 parents 5ead738 + 735d2c9 commit 2e4541f
Showing 1 changed file with 3 additions and 37 deletions.
40 changes: 3 additions & 37 deletions library/constant_time.c
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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++) {
Expand Down

0 comments on commit 2e4541f

Please sign in to comment.