[prev in list] [next in list] [prev in thread] [next in thread] 

List:       gcrypt-devel
Subject:    [PATCH 1/2] Improve constant-time buffer compare
From:       Jussi Kivilinna <jussi.kivilinna () iki ! fi>
Date:       2018-03-11 15:10:49
Message-ID: 152078104967.30895.5002712088528772387.stgit () localhost ! localdomain
[Download RAW message or body]

* cipher/bufhelp.h (buf_eq_const): Rewrite logic.
--

New implementation for constant-time buffer comparing that
avoids generating conditional code in comparison loop.

Signed-off-by: Jussi Kivilinna <jussi.kivilinna@iki.fi>
---
 0 files changed

diff --git a/cipher/bufhelp.h b/cipher/bufhelp.h
index b854bc016..83d3f53aa 100644
--- a/cipher/bufhelp.h
+++ b/cipher/bufhelp.h
@@ -290,13 +290,19 @@ buf_eq_const(const void *_a, const void *_b, size_t len)
 {
   const byte *a = _a;
   const byte *b = _b;
-  size_t diff, i;
+  int ab, ba;
+  size_t i;
 
   /* Constant-time compare. */
-  for (i = 0, diff = 0; i < len; i++)
-    diff -= !!(a[i] - b[i]);
+  for (i = 0, ab = 0, ba = 0; i < len; i++)
+    {
+      /* If a[i] != b[i], either ab or ba will be negative. */
+      ab |= a[i] - b[i];
+      ba |= b[i] - a[i];
+    }
 
-  return !diff;
+  /* 'ab | ba' is negative when buffers are not equal. */
+  return (ab | ba) >= 0;
 }
 
 


_______________________________________________
Gcrypt-devel mailing list
Gcrypt-devel@gnupg.org
http://lists.gnupg.org/mailman/listinfo/gcrypt-devel
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic