bssl_crypto/mem.rs
1// Copyright 2023 The BoringSSL Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::FfiSlice;
16
17/// Returns true iff `a` and `b` contain the same bytes. It takes an amount of time dependent on the
18/// lengths, but independent of the contents of the slices `a` and `b`. The return type is a `bool`,
19/// since unlike `memcmp` in C this function cannot be used to put elements into a defined order.
20pub fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
21 if a.len() != b.len() {
22 return false;
23 }
24 if a.is_empty() {
25 // Avoid FFI issues with empty slices that may potentially cause UB
26 return true;
27 }
28 // Safety:
29 // - The lengths of a and b are checked above.
30 let result =
31 unsafe { bssl_sys::CRYPTO_memcmp(a.as_ffi_void_ptr(), b.as_ffi_void_ptr(), a.len()) };
32 result == 0
33}
34
35#[cfg(test)]
36mod test {
37 use super::*;
38
39 #[test]
40 fn test_different_length() {
41 assert!(!constant_time_compare(&[0, 1, 2], &[0]))
42 }
43
44 #[test]
45 fn test_same_length_different_content() {
46 assert!(!constant_time_compare(&[0, 1, 2], &[1, 2, 3]))
47 }
48
49 #[test]
50 fn test_same_content() {
51 assert!(constant_time_compare(&[0, 1, 2], &[0, 1, 2]))
52 }
53
54 #[test]
55 fn test_empty_slices() {
56 assert!(constant_time_compare(&[], &[]))
57 }
58
59 #[test]
60 fn test_empty_slices_different() {
61 assert!(!constant_time_compare(&[], &[0, 1, 2]))
62 }
63}