[PATCH] MPI helper of comparison, Least Leak Intended (was: [PATCH] MPI helper of multiplication, Least Leak Intended)

NIIBE Yutaka gniibe at fsij.org
Fri Feb 7 06:28:43 CET 2025


Hello,

This is not related to modular exponentiation, but another function for
constant-time; MPI comparison by a helper function.

I think that this implementation could be improved.  Anyhow, let us
start having the function for comparison.

diff --git a/mpi/mpi-internal.h b/mpi/mpi-internal.h
index ffe8140a..0840d1fd 100644
--- a/mpi/mpi-internal.h
+++ b/mpi/mpi-internal.h
@@ -304,6 +304,7 @@ void _gcry_mpih_abs_cond (mpi_ptr_t wp, mpi_ptr_t up,
 mpi_ptr_t _gcry_mpih_mod_lli (mpi_ptr_t vp, mpi_size_t vsize,
                               mpi_ptr_t up, mpi_size_t usize);
 int _gcry_mpih_cmp_ui (mpi_ptr_t up, mpi_size_t usize, unsigned long v);
+int _gcry_mpih_cmp_lli (mpi_ptr_t up, mpi_ptr_t vp, mpi_size_t size);
 
 
 /* Define stuff for longlong.h.  */
diff --git a/mpi/mpih-const-time.c b/mpi/mpih-const-time.c
index e684b956..4549ebca 100644
--- a/mpi/mpih-const-time.c
+++ b/mpi/mpih-const-time.c
@@ -239,3 +239,25 @@ _gcry_mpih_cmp_ui (mpi_ptr_t up, mpi_size_t usize, unsigned long v)
     }
   return 1;
 }
+
+/* Do same calculation as _gcry_mpih_cmp does, but Least Leak Intended.
+ * Return 1 if U > V, 0 if they are equal, and -1 if U < V.  */
+int
+_gcry_mpih_cmp_lli (mpi_ptr_t up, mpi_ptr_t vp, mpi_size_t size)
+{
+  mpi_size_t i;
+  mpi_limb_t gt, lt;
+  mpi_limb_t result = 0;
+
+  for (i = 0; i < size ; i++)
+    {
+      gt = mpih_ct_limb_greater_than (up[i], vp[i]);
+      lt = mpih_ct_limb_less_than (up[i], vp[i]);
+      /* result = gt ? 1 : result; */
+      result = (result & (- mpih_limb_is_zero (gt))) | gt;
+      /* result = lt ? -1 : result; */
+      result = (result & (- mpih_limb_is_zero (lt))) | -lt;
+    }
+
+  return result;
+}

-- 



More information about the Gcrypt-devel mailing list