[PATCH 10/12] mpih_cmp_ui: avoid unintentional conditional branch

Jussi Kivilinna jussi.kivilinna at iki.fi
Thu Nov 2 19:06:37 CET 2023


* mpi/mpi-internal.h (mpih_limb_is_zero): New.
* mpi/mpih-const-time.c (_gcry_mpih_cmp_ui): Use mpih_limb_is_zero
instead of comparison.
--

Signed-off-by: Jussi Kivilinna <jussi.kivilinna at iki.fi>
---
 mpi/mpi-internal.h    | 9 +++++++++
 mpi/mpih-const-time.c | 2 +-
 2 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/mpi/mpi-internal.h b/mpi/mpi-internal.h
index 79a6cce7..bb12e86c 100644
--- a/mpi/mpi-internal.h
+++ b/mpi/mpi-internal.h
@@ -267,6 +267,15 @@ mpi_limb_t _gcry_mpih_rshift( mpi_ptr_t wp, mpi_ptr_t up, mpi_size_t usize,
 #define mpih_abs_cond(w,u,s,o) _gcry_mpih_abs_cond ((w),(u),(s),(o))
 #define mpih_mod(v,vs,u,us) _gcry_mpih_mod ((v),(vs),(u),(us))
 
+static inline int
+mpih_limb_is_zero (mpi_limb_t a)
+{
+  /* Sign bit set if A == 0. */
+  a = ~a & ~(-a);
+
+  return a >> (BITS_PER_MPI_LIMB - 1);
+}
+
 void _gcry_mpih_set_cond (mpi_ptr_t wp, mpi_ptr_t up, mpi_size_t usize,
                           unsigned long op_enable);
 mpi_limb_t _gcry_mpih_add_n_cond (mpi_ptr_t wp, mpi_ptr_t up, mpi_ptr_t vp,
diff --git a/mpi/mpih-const-time.c b/mpi/mpih-const-time.c
index 85dba389..3d854e8c 100644
--- a/mpi/mpih-const-time.c
+++ b/mpi/mpih-const-time.c
@@ -202,7 +202,7 @@ _gcry_mpih_cmp_ui (mpi_ptr_t up, mpi_size_t usize, unsigned long v)
   mpi_size_t i;
 
   for (i = 1; i < usize; i++)
-    is_all_zero &= (up[i] == 0);
+    is_all_zero &= mpih_limb_is_zero (up[i]);
 
   if (is_all_zero)
     {
-- 
2.40.1




More information about the Gcrypt-devel mailing list