tor_proto/util/
ct.rs

1//! Constant-time utilities.
2use subtle::{Choice, ConstantTimeEq};
3
4/// Convert a boolean into a Choice.
5///
6/// This isn't necessarily a good idea or constant-time.
7pub(crate) fn bool_to_choice(v: bool) -> Choice {
8    Choice::from(u8::from(v))
9}
10
11/// Return true if two slices are equal.  Performs its operation in constant
12/// time, but returns a bool instead of a subtle::Choice.
13pub(crate) fn bytes_eq(a: &[u8], b: &[u8]) -> bool {
14    let choice = a.ct_eq(b);
15    choice.unwrap_u8() == 1
16}
17
18/// Returns true if all bytes of the input are zero (including if the slice is
19/// empty). Executes in constant time for a given length of input.
20pub(crate) fn is_zero(x: &[u8]) -> bool {
21    // It's tempting to lift the Choice out of the fold loop, s.t. the loop does
22    // a simple bit-or of each byte, but then the compiler could theoretically
23    // exit the loop early if all bits become one (i.e. 0xff). (Granted this
24    // seems unlikely in practice)
25    x.iter()
26        .map(|b| bool_to_choice(*b == 0))
27        .fold(bool_to_choice(true), std::ops::BitAnd::bitand)
28        .unwrap_u8()
29        == 1
30}
31
32#[cfg(test)]
33mod test {
34    // @@ begin test lint list maintained by maint/add_warning @@
35    #![allow(clippy::bool_assert_comparison)]
36    #![allow(clippy::clone_on_copy)]
37    #![allow(clippy::dbg_macro)]
38    #![allow(clippy::mixed_attributes_style)]
39    #![allow(clippy::print_stderr)]
40    #![allow(clippy::print_stdout)]
41    #![allow(clippy::single_char_pattern)]
42    #![allow(clippy::unwrap_used)]
43    #![allow(clippy::unchecked_duration_subtraction)]
44    #![allow(clippy::useless_vec)]
45    #![allow(clippy::needless_pass_by_value)]
46    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
47    #[test]
48    fn test_bytes_eq() {
49        use super::bytes_eq;
50        assert!(bytes_eq(&b"123"[..], &b"1234"[..3]));
51        assert!(!bytes_eq(&b"123"[..], &b"1234"[..]));
52        assert!(bytes_eq(&b"45"[..], &b"45"[..]));
53        assert!(!bytes_eq(&b"hi"[..], &b"45"[..]));
54        assert!(bytes_eq(&b""[..], &b""[..]));
55    }
56
57    #[test]
58    fn test_is_zero() {
59        use super::is_zero;
60        assert!(is_zero(&[]));
61        assert!(is_zero(&[0]));
62        assert!(is_zero(&[0, 0]));
63        assert!(!is_zero(&[1, 0]));
64        assert!(!is_zero(&[0, 1]));
65        assert!(!is_zero(&[0, 1, 0]));
66    }
67}