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

NIIBE Yutaka via Gcrypt-devel <[email protected]>
Newsgroups gmane.comp.encryption.gpg.libgcrypt.devel
Message-ID <[email protected]>
NIIBE Yutaka <[email protected]> wrote:
> I think that this implementation could be improved.

I should use ct_limb_gen_inv_mask function instead of directly use unary
minus operator.

--

_______________________________________________
Gcrypt-devel mailing list
[email protected]
https://lists.gnupg.org/mailman/listinfo/gcrypt-devel
0001-mpi-Add-_gcry_mpih_cmp_lli-for-Least-Leak-Intended-c.patch (text/x-diff, 1.9 KB)
>From 6edebbb2573e1a0e1bc66b6c5162826e579795c1 Mon Sep 17 00:00:00 2001
From: NIIBE Yutaka <[email protected]>
Date: Sat, 8 Feb 2025 11:00:18 +0900
Subject: [PATCH] mpi: Add _gcry_mpih_cmp_lli for Least Leak Intended
 comparison.

* mpi/mpi-internal.h (_gcry_mpih_cmp_lli): New.
* mpi/mpih-const-time.c (_gcry_mpih_cmp_lli): New.

--

Signed-off-by: NIIBE Yutaka <[email protected]>
---
 mpi/mpi-internal.h    |  1 +
 mpi/mpih-const-time.c | 22 ++++++++++++++++++++++
 2 files changed, 23 insertions(+)

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..7c783492 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 & ct_limb_gen_inv_mask (gt)) | gt;
+      /* result = lt ? -1 : result; */
+      result = (result & ct_limb_gen_inv_mask (lt)) | -lt;
+    }
+
+  return (int)result;
+}
-- 
2.39.5
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.