1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6    @file mem_neq.c
7    Compare two blocks of memory for inequality in constant time.
8    Steffen Jaeckel
9 */
10 
11 /**
12    Compare two blocks of memory for inequality in constant time.
13 
14    The usage is similar to that of standard memcmp, but you can only test
15    if the memory is equal or not - you can not determine by how much the
16    first different byte differs.
17 
18    This function shall be used to compare results of cryptographic
19    operations where inequality means most likely usage of a wrong key.
20    The execution time has therefore to be constant as otherwise
21    timing attacks could be possible.
22 
23    @param a     The first memory region
24    @param b     The second memory region
25    @param len   The length of the area to compare (octets)
26 
27    @return 0 when a and b are equal for len bytes, 1 they are not equal.
28 */
mem_neq(const void * a,const void * b,size_t len)29 int mem_neq(const void *a, const void *b, size_t len)
30 {
31    unsigned char ret = 0;
32    const unsigned char* pa;
33    const unsigned char* pb;
34 
35    LTC_ARGCHK(a != NULL);
36    LTC_ARGCHK(b != NULL);
37 
38    pa = a;
39    pb = b;
40 
41    while (len-- > 0) {
42       ret |= *pa ^ *pb;
43       ++pa;
44       ++pb;
45    }
46 
47    ret |= ret >> 4;
48    ret |= ret >> 2;
49    ret |= ret >> 1;
50    ret &= 1;
51 
52    return ret;
53 }
54