[PATCH 06/12] const-time: ct_memmov_cond: switch to use dual mask approach

Jussi Kivilinna jussi.kivilinna at iki.fi
Thu Nov 2 19:01:10 CET 2023


* src/const-time.c (_gcry_ct_memmov_cond): Use dual mask + AND/OR
instead of single mask + XOR.
--

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

diff --git a/src/const-time.c b/src/const-time.c
index 2066d48d..73bf8b40 100644
--- a/src/const-time.c
+++ b/src/const-time.c
@@ -74,12 +74,13 @@ void
 _gcry_ct_memmov_cond (void *dst, const void *src, size_t len,
 		      unsigned long op_enable)
 {
-  size_t i;
-  unsigned char mask;
+  /* Note: dual mask with AND/OR used for EM leakage mitigation */
+  unsigned char mask1 = _gcry_ct_vzero - op_enable;
+  unsigned char mask2 = op_enable - _gcry_ct_vone;
   unsigned char *b_dst = dst;
   const unsigned char *b_src = src;
+  size_t i;
 
-  mask = -(unsigned char)op_enable;
   for (i = 0; i < len; i++)
-    b_dst[i] ^= mask & (b_dst[i] ^ b_src[i]);
+    b_dst[i] = (b_dst[i] & mask2) | (b_src[i] & mask1);
 }
-- 
2.40.1




More information about the Gcrypt-devel mailing list