1 #include <stddef.h>
2 #include <stdint.h>
3 #include "verify.h"
4
5 /*************************************************
6 * Name: verify
7 *
8 * Description: Compare two arrays for equality in constant time.
9 *
10 * Arguments: const uint8_t *a: pointer to first byte array
11 * const uint8_t *b: pointer to second byte array
12 * size_t len: length of the byte arrays
13 *
14 * Returns 0 if the byte arrays are equal, 1 otherwise
15 **************************************************/
verify(const uint8_t * a,const uint8_t * b,size_t len)16 int verify(const uint8_t *a, const uint8_t *b, size_t len)
17 {
18 size_t i;
19 uint8_t r = 0;
20
21 for(i=0;i<len;i++)
22 r |= a[i] ^ b[i];
23
24 return (-(uint64_t)r) >> 63;
25 }
26
27 /*************************************************
28 * Name: cmov
29 *
30 * Description: Copy len bytes from x to r if b is 1;
31 * don't modify x if b is 0. Requires b to be in {0,1};
32 * assumes two's complement representation of negative integers.
33 * Runs in constant time.
34 *
35 * Arguments: uint8_t *r: pointer to output byte array
36 * const uint8_t *x: pointer to input byte array
37 * size_t len: Amount of bytes to be copied
38 * uint8_t b: Condition bit; has to be in {0,1}
39 **************************************************/
cmov(uint8_t * r,const uint8_t * x,size_t len,uint8_t b)40 void cmov(uint8_t *r, const uint8_t *x, size_t len, uint8_t b)
41 {
42 size_t i;
43
44 b = -b;
45 for(i=0;i<len;i++)
46 r[i] ^= b & (r[i] ^ x[i]);
47 }
48