Blame


1 f9ab77a8 2023-08-23 op /* $OpenBSD: timingsafe_memcmp.c,v 1.2 2015/08/31 02:53:57 guenther Exp $ */
2 f9ab77a8 2023-08-23 op /*
3 f9ab77a8 2023-08-23 op * Copyright (c) 2014 Google Inc.
4 f9ab77a8 2023-08-23 op *
5 f9ab77a8 2023-08-23 op * Permission to use, copy, modify, and distribute this software for any
6 f9ab77a8 2023-08-23 op * purpose with or without fee is hereby granted, provided that the above
7 f9ab77a8 2023-08-23 op * copyright notice and this permission notice appear in all copies.
8 f9ab77a8 2023-08-23 op *
9 f9ab77a8 2023-08-23 op * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 f9ab77a8 2023-08-23 op * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 f9ab77a8 2023-08-23 op * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 f9ab77a8 2023-08-23 op * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 f9ab77a8 2023-08-23 op * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 f9ab77a8 2023-08-23 op * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 f9ab77a8 2023-08-23 op * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 f9ab77a8 2023-08-23 op */
17 f9ab77a8 2023-08-23 op
18 f9ab77a8 2023-08-23 op #include "../config.h"
19 f9ab77a8 2023-08-23 op
20 f9ab77a8 2023-08-23 op #include <limits.h>
21 f9ab77a8 2023-08-23 op #include <string.h>
22 f9ab77a8 2023-08-23 op
23 f9ab77a8 2023-08-23 op int
24 f9ab77a8 2023-08-23 op timingsafe_memcmp(const void *b1, const void *b2, size_t len)
25 f9ab77a8 2023-08-23 op {
26 f9ab77a8 2023-08-23 op const unsigned char *p1 = b1, *p2 = b2;
27 f9ab77a8 2023-08-23 op size_t i;
28 f9ab77a8 2023-08-23 op int res = 0, done = 0;
29 f9ab77a8 2023-08-23 op
30 f9ab77a8 2023-08-23 op for (i = 0; i < len; i++) {
31 f9ab77a8 2023-08-23 op /* lt is -1 if p1[i] < p2[i]; else 0. */
32 f9ab77a8 2023-08-23 op int lt = (p1[i] - p2[i]) >> CHAR_BIT;
33 f9ab77a8 2023-08-23 op
34 f9ab77a8 2023-08-23 op /* gt is -1 if p1[i] > p2[i]; else 0. */
35 f9ab77a8 2023-08-23 op int gt = (p2[i] - p1[i]) >> CHAR_BIT;
36 f9ab77a8 2023-08-23 op
37 f9ab77a8 2023-08-23 op /* cmp is 1 if p1[i] > p2[i]; -1 if p1[i] < p2[i]; else 0. */
38 f9ab77a8 2023-08-23 op int cmp = lt - gt;
39 f9ab77a8 2023-08-23 op
40 f9ab77a8 2023-08-23 op /* set res = cmp if !done. */
41 f9ab77a8 2023-08-23 op res |= cmp & ~done;
42 f9ab77a8 2023-08-23 op
43 f9ab77a8 2023-08-23 op /* set done if p1[i] != p2[i]. */
44 f9ab77a8 2023-08-23 op done |= lt | gt;
45 f9ab77a8 2023-08-23 op }
46 f9ab77a8 2023-08-23 op
47 f9ab77a8 2023-08-23 op return (res);
48 f9ab77a8 2023-08-23 op }