boring/memcmp.rs
1//! Utilities to safely compare cryptographic values.
2//!
3//! Extra care must be taken when comparing values in
4//! cryptographic code. If done incorrectly, it can lead
5//! to a [timing attack](https://en.wikipedia.org/wiki/Timing_attack).
6//! By analyzing the time taken to execute parts of a cryptographic
7//! algorithm, and attacker can attempt to compromise the
8//! cryptosystem.
9//!
10//! The utilities in this module are designed to be resistant
11//! to this type of attack.
12//!
13//! # Examples
14//!
15//! To perform a constant-time comparison of two arrays of the same length but different
16//! values:
17//!
18//! ```
19//! use boring::memcmp::eq;
20//!
21//! // We want to compare `a` to `b` and `c`, without giving
22//! // away through timing analysis that `c` is more similar to `a`
23//! // than `b`.
24//! let a = [0, 0, 0];
25//! let b = [1, 1, 1];
26//! let c = [0, 0, 1];
27//!
28//! // These statements will execute in the same amount of time.
29//! assert!(!eq(&a, &b));
30//! assert!(!eq(&a, &c));
31//! ```
32use crate::ffi;
33
34/// Returns `true` iff `a` and `b` contain the same bytes.
35///
36/// This operation takes an amount of time dependent on the length of the two
37/// arrays given, but is independent of the contents of a and b.
38///
39/// # Panics
40///
41/// This function will panic the current task if `a` and `b` do not have the same
42/// length.
43///
44/// # Examples
45///
46/// To perform a constant-time comparison of two arrays of the same length but different
47/// values:
48///
49/// ```
50/// use boring::memcmp::eq;
51///
52/// // We want to compare `a` to `b` and `c`, without giving
53/// // away through timing analysis that `c` is more similar to `a`
54/// // than `b`.
55/// let a = [0, 0, 0];
56/// let b = [1, 1, 1];
57/// let c = [0, 0, 1];
58///
59/// // These statements will execute in the same amount of time.
60/// assert!(!eq(&a, &b));
61/// assert!(!eq(&a, &c));
62/// ```
63#[must_use]
64pub fn eq(a: &[u8], b: &[u8]) -> bool {
65 assert!(a.len() == b.len());
66 let ret = unsafe { ffi::CRYPTO_memcmp(a.as_ptr().cast(), b.as_ptr().cast(), a.len()) };
67 ret == 0
68}
69
70#[cfg(test)]
71mod tests {
72 use super::eq;
73
74 #[test]
75 fn test_eq() {
76 assert!(eq(&[], &[]));
77 assert!(eq(&[1], &[1]));
78 assert!(!eq(&[1, 2, 3], &[1, 2, 4]));
79 }
80
81 #[test]
82 #[should_panic]
83 fn test_diff_lens() {
84 let _ = eq(&[], &[1]);
85 }
86}