diff --git a/library/constant_time_impl.h b/library/constant_time_impl.h index 971388c19..54bd2b0ed 100644 --- a/library/constant_time_impl.h +++ b/library/constant_time_impl.h @@ -183,8 +183,14 @@ static inline mbedtls_ct_condition_t mbedtls_ct_bool(mbedtls_ct_uint_t x) #pragma warning( push ) #pragma warning( disable : 4146 ) #endif - return (mbedtls_ct_condition_t) (((mbedtls_ct_int_t) ((-xo) | -(xo >> 1))) >> - (MBEDTLS_CT_SIZE - 1)); + // y is negative (i.e., top bit set) iff x is non-zero + mbedtls_ct_int_t y = (-xo) | -(xo >> 1); + + // extract only the sign bit of y so that y == 1 (if x is non-zero) or 0 (if x is zero) + y = (((mbedtls_ct_uint_t) y) >> (MBEDTLS_CT_SIZE - 1)); + + // -y has all bits set (if x is non-zero), or all bits clear (if x is zero) + return (mbedtls_ct_condition_t) (-y); #if defined(_MSC_VER) #pragma warning( pop ) #endif