util: Add memcmp_const_time()
authorAndreas Schneider <asn@samba.org>
Fri, 1 Apr 2016 08:09:45 +0000 (10:09 +0200)
committerAndreas Schneider <asn@cryptomilk.org>
Tue, 19 Apr 2016 07:37:14 +0000 (09:37 +0200)
Signed-off-by: Andreas Schneider <asn@samba.org>
Reviewed-by: Jeremy Allison <jra@samba.org>
lib/util/samba_util.h
lib/util/util_str.c

index 9d6f0d8bf26bd810f549802f84d258c426a50825..387e957ceca23c59735286b18482bf0412bfdd1f 100644 (file)
@@ -279,6 +279,19 @@ limited by 'n' bytes
 _PUBLIC_ size_t utf16_len_n(const void *src, size_t n);
 _PUBLIC_ size_t ucs2_align(const void *base_ptr, const void *p, int flags);
 
+/**
+ * @brief Constant time compare to memory regions.
+ *
+ * @param[in]  s1  The first memory region to compare.
+ *
+ * @param[in]  s2  The second memory region to compare.
+ *
+ * @param[in]  n   The length of the memory to comapre.
+ *
+ * @return 0 when the memory regions are equal, 0 if not.
+ */
+_PUBLIC_ int memcmp_const_time(const void *s1, const void *s2, size_t n);
+
 /**
 Do a case-insensitive, whitespace-ignoring string compare.
 **/
index 673fbc7c6b5ebac23a88020eb0510afb77b1e0cd..c7d91ca3744b63aa80a13c55b72e1e2296b82f6f 100644 (file)
@@ -333,3 +333,15 @@ _PUBLIC_ size_t utf16_len_n(const void *src, size_t n)
 
        return len;
 }
+
+_PUBLIC_ int memcmp_const_time(const void *s1, const void *s2, size_t n)
+{
+       const uint8_t *p1 = s1, *p2 = s2;
+       size_t i, sum = 0;
+
+       for (i = 0; i < n; i++) {
+               sum |= (p1[i] ^ p2[i]);
+       }
+
+       return sum != 0;
+}