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
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).
///
/// 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)));
/// ```
///
/// ## 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`.
/// * The derive works with generics and const generics; your field types must still satisfy `TimingSafeEq`.
///
impl_timing_safe_eq!;