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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
pub use Choice;
use ConstantTimeEq;
/// This module defines the [`TimingSafeEq`] trait for performing equality
/// checks in constant-time with respect to secret data, and the
/// [`TimingSafeEq`] derive macro to automatically implement it for structs and enums.
///
/// ## Overview
///
/// * [`TimingSafeEq`] – compare two values in constant-time, returning a
/// [`Choice`] instead of a `bool`.
/// * [`TimingSafeEq`] – derive macro that implements [`TimingSafeEq`] and
/// [`PartialEq`]/[`Eq`] by combining all fields’ `ts_eq` results with bitwise AND.
///
/// The derive requires that all fields of the type implement
/// [`TimingSafeEq`], which you can do manually for your own field types
/// or via blanket impls (e.g., for arrays and references).
///
/// Implementations are provided for the integer primitives, `bool`, `f32` and
/// `f64` (bit-pattern equality, see the impl docs), `str`, `String`, `[u8]`,
/// `Vec<u8>`, `[T; N]`, and `&T` for any `T: TimingSafeEq`.
///
/// The variable-length impls (`str`, `String`, `[u8]`, `Vec<u8>`) report a
/// length mismatch as unequal without comparing contents, as `subtle`'s
/// slice comparison does, so a length is never treated as secret.
///
/// Implementations of [`TimingSafeEq`] for many common types are included and internally use the [subtle](https://crates.io/crates/subtle) crate.
///
/// ## Examples
///
/// ### Implementing `TimingSafeEq` manually
///
/// ```
/// # mod vitaminc { pub mod protected { pub use vitaminc_protected::*; } }
/// use vitaminc::protected::{TimingSafeEq, Choice};
///
/// #[derive(Clone, Copy)]
/// struct CtU8(u8);
///
/// impl TimingSafeEq for CtU8 {
/// fn ts_eq(&self, other: &Self) -> Choice {
/// // Branchless equality: (x ^ y) == 0
/// let x = self.0 ^ other.0;
/// Choice::from((x == 0) as u8)
/// }
/// }
/// ```
///
/// ### Using `#[derive(TimingSafeEq)]`
///
/// ```
/// # mod vitaminc { pub mod protected { pub use vitaminc_protected::*; } }
/// use vitaminc::protected::{TimingSafeEq, Choice};
///
/// #[derive(TimingSafeEq)]
/// struct Key<const N: usize>([u8; N]);
///
/// let k1 = Key::<3>([1, 2, 3]);
/// let k2 = Key::<3>([1, 2, 3]);
/// let k3 = Key::<3>([1, 2, 4]);
///
/// assert!(k1 == k2); // uses constant-time compare internally
/// assert!(bool::from(k1.ts_eq(&k2)));
///
/// assert!(k1 != k3);
/// assert!(!bool::from(k1.ts_eq(&k3)));
/// ```
///
/// ### Naming the crate
///
/// The generated impls name `TimingSafeEq` and `Choice` by path, so no `use`
/// is needed where the derive is applied. The derive finds that path in your
/// `Cargo.toml`: a dependency on `vitaminc-protected` (under any name), or on
/// `vitaminc` with the `protected` feature (`vitaminc::protected`). If you
/// reach the crate some other way, such as a re-export, name it yourself:
///
/// ```
/// mod reexport { pub mod protected { pub use vitaminc_protected::*; } }
///
/// #[derive(vitaminc_protected::TimingSafeEq)]
/// #[timing_safe(crate = "reexport::protected")]
/// struct Key([u8; 4]);
///
/// assert!(Key([1, 2, 3, 4]) == Key([1, 2, 3, 4]));
/// ```
///
/// ## Notes
///
/// * The derive performs a field-wise AND of all `ts_eq` results; if any field differs, the result is `Choice(0)`.
/// * All fields must implement `TimingSafeEq`, or the derive will fail to compile.
/// * `PartialEq`/`Eq` are implemented in terms of `ts_eq` and return `bool`.
/// * Do not derive `PartialOrd` or `Ord` from std beside this derive on a type
/// with `f32` or `f64` fields. The derived `PartialEq` is bit-pattern
/// equality (see the float impls), while std's `PartialOrd` for floats is
/// IEEE ordering, so `a == b` would not imply `partial_cmp(a, b) ==
/// Some(Equal)` (two equal `NaN`s, or `0.0` and `-0.0`), which `PartialOrd`
/// requires. Nothing warns about it. Write the ordering by hand if the type
/// needs one.
/// * The derive works with generics and const generics; your field types must still satisfy `TimingSafeEq`.
///
/// Forwards to `T`, so a reference compares exactly as the value it points at.
///
/// This is what lets `#[derive(TimingSafeEq)]` handle borrowed fields such as
/// `&'a str` and `&'a [u8]`: the derive compares fields by reference, so a
/// `&'a [u8]` field is compared as `&&[u8]`, which needs `&[u8]: TimingSafeEq`.
///
/// A blanket impl is a one-way door (a downstream crate can no longer write
/// its own `impl TimingSafeEq for &Theirs`), which is why there is no `&mut T`
/// impl: nothing needs one yet.
/// Compares the UTF-8 bytes in constant time.
impl_timing_safe_eq!;
/// Compares the two booleans as `u8` (`0` or `1`) in constant time.
/// Bit-pattern equality, **not** IEEE 754 `==`.
///
/// The two values are equal when [`f32::to_bits`] returns the same `u32` for
/// both, compared in constant time. This differs from `==` in two places:
///
/// * a `NaN` equals itself (and any `NaN` with the same sign and payload),
/// whereas `NaN == NaN` is `false`; two `NaN`s with different payloads are
/// unequal;
/// * `-0.0` and `0.0` are unequal, whereas `-0.0 == 0.0` is `true`.
///
/// Bit-pattern equality is the only definition that is both constant time and
/// well defined for every value: IEEE `==` needs data-dependent special cases
/// for `NaN` and signed zero, and is not reflexive, so it cannot back
/// [`Eq`]. It is also what a sealed float needs, since the bits are what gets
/// encrypted, and two floats that encrypt from different bits are different
/// plaintexts.
///
/// Because of this, do not derive `PartialOrd` or `Ord` from std on a type
/// whose `PartialEq` comes from `#[derive(TimingSafeEq)]` and holds a float:
/// std's float ordering is IEEE, so `a == b` would not imply
/// `partial_cmp(a, b) == Some(Equal)`.
/// Bit-pattern equality, **not** IEEE 754 `==`.
///
/// The two values are equal when [`f64::to_bits`] returns the same `u64` for
/// both, compared in constant time. This differs from `==` in two places:
///
/// * a `NaN` equals itself (and any `NaN` with the same sign and payload),
/// whereas `NaN == NaN` is `false`; two `NaN`s with different payloads are
/// unequal;
/// * `-0.0` and `0.0` are unequal, whereas `-0.0 == 0.0` is `true`.
///
/// Bit-pattern equality is the only definition that is both constant time and
/// well defined for every value: IEEE `==` needs data-dependent special cases
/// for `NaN` and signed zero, and is not reflexive, so it cannot back
/// [`Eq`]. It is also what a sealed float needs, since the bits are what gets
/// encrypted, and two floats that encrypt from different bits are different
/// plaintexts.
///
/// Because of this, do not derive `PartialOrd` or `Ord` from std on a type
/// whose `PartialEq` comes from `#[derive(TimingSafeEq)]` and holds a float:
/// std's float ordering is IEEE, so `a == b` would not imply
/// `partial_cmp(a, b) == Some(Equal)`.