[PATCH 1/2] Improve constant-time buffer compare
Jussi Kivilinna
jussi.kivilinna at iki.fi
Sun Mar 11 16:10:49 CET 2018
* 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 at 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;
}
More information about the Gcrypt-devel
mailing list