1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
//! Constant-Time Comparison for SHA3-512 Digests
//!
//! Implements timing-safe equality comparison to prevent side-channel
//! attacks when verifying hash digests. A naive byte-by-byte comparison
//! with early exit leaks information about which byte position differs
//! first, enabling an adversary to iteratively reconstruct a target
//! digest (Kocher, 1996).
//!
//! # Algorithm
//!
//! The comparison accumulates the XOR of every byte pair into a single
//! accumulator. The result is zero if and only if all bytes are equal.
//! Every byte is always visited regardless of where a difference occurs,
//! ensuring constant execution time relative to the digest length.
//!
//! # References
//!
//! - Kocher, P.C. (1996) 'Timing Attacks on Implementations of
//! Diffie-Hellman, RSA, DSS, and Other Systems', in *Advances in
//! Cryptology — CRYPTO '96*. Lecture Notes in Computer Science,
//! vol. 1109. Berlin: Springer, pp. 104–113.
//! doi:10.1007/3-540-68697-5_9.
//!
//! - Bernstein, D.J., Lange, T. and Schwabe, P. (2012) 'The Security
//! Impact of a New Cryptographic Library', in *Progress in Cryptology
//! — LATINCRYPT 2012*. Lecture Notes in Computer Science, vol. 7533.
//! Berlin: Springer, pp. 159–176.
/// Compare two byte slices in constant time.
///
/// Returns `true` if and only if `a` and `b` have equal length and
/// identical contents. The execution time depends only on the length
/// of the slices, never on the position of the first differing byte.
///
/// # Examples
///
/// ```
/// use sha3_kernel_hasher::ct::ct_eq;
///
/// let a = [0xABu8; 64];
/// let b = [0xABu8; 64];
/// assert!(ct_eq(&a, &b));
/// ```
/// Compare two 64-byte SHA3-512 digests in constant time.
///
/// This is a specialised version of [`ct_eq`] that operates on
/// fixed-size arrays, eliminating the length check and enabling
/// the compiler to unroll the loop.
///
/// # Examples
///
/// ```
/// use sha3_kernel_hasher::ct::ct_hash_eq;
///
/// let h1 = [0u8; 64];
/// let h2 = [0u8; 64];
/// assert!(ct_hash_eq(&h1, &h2));
/// ```
/// Select between two values in constant time based on a boolean
/// condition.
///
/// Returns `a` if `condition` is `true`, otherwise `b`. Both branches
/// are always evaluated; the selection is performed with bitwise
/// operations to avoid branch prediction leakage.
///
/// # Examples
///
/// ```
/// use sha3_kernel_hasher::ct::ct_select;
///
/// assert_eq!(ct_select(true, 0xAA, 0xBB), 0xAA);
/// assert_eq!(ct_select(false, 0xAA, 0xBB), 0xBB);
/// ```