[PATCH 2/2] mpih-const-time: use constant-time comparisons conditional add/sub/abs

Jussi Kivilinna jussi.kivilinna at iki.fi
Thu Nov 2 20:27:50 CET 2023


* mpi/mpih-const-time.c (mpih_ct_limb_greater_than)
(mpih_ct_limb_less_than): New.
(_gcry_mpih_add_n_cond, _gcry_mpih_sub_n_cond, _gcry_mpih_abs_cond): Use
mpih_ct_limb_greater_than and mpih_ct_limb_less_than for comparisons.
--

Signed-off-by: Jussi Kivilinna <jussi.kivilinna at iki.fi>
---
 mpi/mpih-const-time.c | 33 ++++++++++++++++++++++++++++-----
 1 file changed, 28 insertions(+), 5 deletions(-)

diff --git a/mpi/mpih-const-time.c b/mpi/mpih-const-time.c
index 4ebd072d..2300c666 100644
--- a/mpi/mpih-const-time.c
+++ b/mpi/mpih-const-time.c
@@ -23,6 +23,7 @@
 #include "mpi-internal.h"
 #include "g10lib.h"
 #include "const-time.h"
+#include "longlong.h"
 
 #define A_LIMB_1 ((mpi_limb_t)1)
 
@@ -31,6 +32,28 @@ DEFINE_CT_TYPE_GEN_MASK(limb, mpi_limb_t)
 DEFINE_CT_TYPE_GEN_INV_MASK(limb, mpi_limb_t)
 
 
+/*
+ * Return 1 if X > Y and otherwise return 0.
+ */
+static mpi_limb_t
+mpih_ct_limb_greater_than (mpi_limb_t x, mpi_limb_t y)
+{
+  mpi_limb_t diff_hi, diff_lo;
+  sub_ddmmss (diff_hi, diff_lo, 0, y, 0, x);
+  return diff_hi >> (BITS_PER_MPI_LIMB - 1);
+}
+
+
+/*
+ * Return 1 if X < Y and otherwise return 0.
+ */
+static mpi_limb_t
+mpih_ct_limb_less_than (mpi_limb_t x, mpi_limb_t y)
+{
+  return mpih_ct_limb_greater_than (y, x);
+}
+
+
 /*
  *  W = U when OP_ENABLED=1
  *  otherwise, W keeps old value
@@ -70,11 +93,11 @@ _gcry_mpih_add_n_cond (mpi_ptr_t wp, mpi_ptr_t up, mpi_ptr_t vp,
     {
       mpi_limb_t u = up[i];
       mpi_limb_t x = u + vp[i];
-      mpi_limb_t cy1 = x < u;
+      mpi_limb_t cy1 = mpih_ct_limb_less_than(x, u);
       mpi_limb_t cy2;
 
       x = x + cy;
-      cy2 = x < cy;
+      cy2 = mpih_ct_limb_less_than(x, cy);
       cy = cy1 | cy2;
       wp[i] = (u & mask2) | (x & mask1);
     }
@@ -102,10 +125,10 @@ _gcry_mpih_sub_n_cond (mpi_ptr_t wp, mpi_ptr_t up, mpi_ptr_t vp,
     {
       mpi_limb_t u = up[i];
       mpi_limb_t x = u - vp[i];
-      mpi_limb_t cy1 = x > u;
+      mpi_limb_t cy1 = mpih_ct_limb_greater_than(x, u);
       mpi_limb_t cy2;
 
-      cy2 = x < cy;
+      cy2 = mpih_ct_limb_less_than(x, cy);
       x = x - cy;
       cy = cy1 | cy2;
       wp[i] = (u & mask2) | (x & mask1);
@@ -157,7 +180,7 @@ _gcry_mpih_abs_cond (mpi_ptr_t wp, mpi_ptr_t up, mpi_size_t usize,
       mpi_limb_t u = up[i];
       mpi_limb_t x = ~u + cy;
 
-      cy = (x < ~u);
+      cy = mpih_ct_limb_less_than(x, ~u);
       wp[i] = (u & mask2) | (x & mask1);
     }
 }
-- 
2.40.1




More information about the Gcrypt-devel mailing list