Skip to main content

bssl_crypto/
mem.rs

1/* Copyright 2023 The BoringSSL Authors
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 */
15
16use crate::FfiSlice;
17
18/// Returns true iff `a` and `b` contain the same bytes. It takes an amount of time dependent on the
19/// lengths, but independent of the contents of the slices `a` and `b`. The return type is a `bool`,
20/// since unlike `memcmp` in C this function cannot be used to put elements into a defined order.
21pub fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
22    if a.len() != b.len() {
23        return false;
24    }
25    if a.is_empty() {
26        // Avoid FFI issues with empty slices that may potentially cause UB
27        return true;
28    }
29    // Safety:
30    // - The lengths of a and b are checked above.
31    let result =
32        unsafe { bssl_sys::CRYPTO_memcmp(a.as_ffi_void_ptr(), b.as_ffi_void_ptr(), a.len()) };
33    result == 0
34}
35
36#[cfg(test)]
37mod test {
38    use super::*;
39
40    #[test]
41    fn test_different_length() {
42        assert!(!constant_time_compare(&[0, 1, 2], &[0]))
43    }
44
45    #[test]
46    fn test_same_length_different_content() {
47        assert!(!constant_time_compare(&[0, 1, 2], &[1, 2, 3]))
48    }
49
50    #[test]
51    fn test_same_content() {
52        assert!(constant_time_compare(&[0, 1, 2], &[0, 1, 2]))
53    }
54
55    #[test]
56    fn test_empty_slices() {
57        assert!(constant_time_compare(&[], &[]))
58    }
59
60    #[test]
61    fn test_empty_slices_different() {
62        assert!(!constant_time_compare(&[], &[0, 1, 2]))
63    }
64}