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
//
// Copyright 2020 Signal Messenger, LLC.
// SPDX-License-Identifier: AGPL-3.0-only
//

use std::cmp::Ordering;
use std::ops::{Add, Div, Rem};

fn expand_top_bit(a: u8) -> u8 {
    //if (a >> 7) == 1 { 0xFF } else { 0 }
    0u8.wrapping_sub(a >> 7)
}

fn ct_is_zero(a: u8) -> u8 {
    //if a == 0 { 0xFF } else { 0 }
    expand_top_bit(!a & a.wrapping_sub(1))
}

fn ct_is_eq(a: u8, b: u8) -> u8 {
    //if a == b { 0xFF } else { 0 }
    ct_is_zero(a ^ b)
}

fn ct_is_lt(a: u8, b: u8) -> u8 {
    //if a < b { 0xFF } else { 0 }
    expand_top_bit(a ^ ((a ^ b) | ((a.wrapping_sub(b)) ^ a)))
}

fn ct_select(mask: u8, a: u8, b: u8) -> u8 {
    debug_assert!(mask == 0 || mask == 0xFF);
    //if mask == 0xFF { a } else if mask == 0x00 { b } else { unreachable!(); }
    b ^ (mask & (a ^ b))
}

/*
* If x and y are different lengths, this leaks information about
* their relative sizes. This is irrelevant as we always invoke it
* with two inputs of the same size.
*
* In addition it will leak the final comparison result, when the
* integer is translated to the Ordering enum. This seems unavoidable.
*
* The primary goal of this function is to not leak any additional
* information, besides the ordering, about the value of the two keys,
* say due to an early exit of the loop.
*
* It would be possible to instead have this function SHA-256 hash both
* inputs, then compare the resulting hashes in the usual non-const
* time way. We avoid this approach at the moment since it is not clear
* if applications will rely on public key ordering being defined in
* some particular way or not.
 */

pub(crate) fn constant_time_cmp(x: &[u8], y: &[u8]) -> Ordering {
    if x.len() < y.len() {
        return Ordering::Less;
    }
    if x.len() > y.len() {
        return Ordering::Greater;
    }

    let mut result: u8 = 0;

    for i in 0..x.len() {
        let a = x[x.len() - 1 - i];
        let b = y[x.len() - 1 - i];

        let is_eq = ct_is_eq(a, b);
        let is_lt = ct_is_lt(a, b);

        result = ct_select(is_eq, result, ct_select(is_lt, 1, 255));
    }

    debug_assert!(result == 0 || result == 1 || result == 255);

    if result == 0 {
        Ordering::Equal
    } else if result == 1 {
        Ordering::Less
    } else {
        Ordering::Greater
    }
}

// To be replaced by 1.73's div_ceil when we update our MSRV.
#[inline]
pub(crate) fn div_ceil<
    T: Copy + Div<Output = T> + Rem<Output = T> + Add<Output = T> + Ord + From<u8>,
>(
    dividend: T,
    divisor: T,
) -> T {
    // From the std implementation of div_ceil.
    let q = dividend / divisor;
    let r = dividend % divisor;
    if (r > 0u8.into() && divisor > 0u8.into()) || (r < 0u8.into() && divisor < 0u8.into()) {
        q + 1u8.into()
    } else {
        q
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_constant_time_cmp() {
        use rand::Rng;

        assert_eq!(constant_time_cmp(&[1], &[1]), Ordering::Equal);
        assert_eq!(constant_time_cmp(&[0, 1], &[1]), Ordering::Greater);
        assert_eq!(constant_time_cmp(&[1], &[0, 1]), Ordering::Less);
        assert_eq!(constant_time_cmp(&[2], &[1, 0, 1]), Ordering::Less);

        let mut rng = rand::rngs::OsRng;
        for len in 1..320 {
            let x: Vec<u8> = (0..len).map(|_| rng.gen()).collect();
            let y: Vec<u8> = (0..len).map(|_| rng.gen()).collect();
            let expected = x.cmp(&y);
            let result = constant_time_cmp(&x, &y);
            assert_eq!(result, expected);

            let expected = y.cmp(&x);
            let result = constant_time_cmp(&y, &x);
            assert_eq!(result, expected);
        }
    }

    #[test]
    fn test_ct_is_zero() {
        assert_eq!(ct_is_zero(0), 0xFF);

        for i in 1..255 {
            assert_eq!(ct_is_zero(i), 0x00);
        }
    }

    #[test]
    fn test_ct_is_lt() {
        for x in 0..255 {
            for y in 0..255 {
                let expected = if x < y { 0xFF } else { 0 };
                let result = ct_is_lt(x, y);
                assert_eq!(result, expected);
            }
        }
    }

    #[test]
    fn test_ct_is_eq() {
        for x in 0..255 {
            for y in 0..255 {
                let expected = if x == y { 0xFF } else { 0 };
                let result = ct_is_eq(x, y);
                assert_eq!(result, expected);
            }
        }
    }

    #[test]
    fn test_div_ceil() {
        assert_eq!(div_ceil(0_usize, 4), 0);
        assert_eq!(div_ceil(7_usize, 4), 2);
        assert_eq!(div_ceil(8_usize, 4), 2);
        assert_eq!(div_ceil(9_usize, 4), 3);
    }

    #[test]
    #[should_panic]
    fn test_div_ceil_panic() {
        _ = div_ceil(4_usize, 0);
    }

    // From https://doc.rust-lang.org/std/primitive.isize.html#method.div_ceil
    #[test]
    fn test_div_ceil_isize() {
        let a: isize = 8;
        let b = 3;

        assert_eq!(div_ceil(a, b), 3);
        assert_eq!(div_ceil(a, -b), -2);
        assert_eq!(div_ceil(-a, b), -2);
        assert_eq!(div_ceil(-a, -b), 3);
    }
}