]>
git.proxmox.com Git - cargo.git/blob - vendor/openssl/src/memcmp.rs
1 //! Utilities to safely compare cryptographic values.
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
10 //! The utilities in this module are designed to be resistant
11 //! to this type of attack.
15 //! To perform a constant-time comparison of two arrays of the same length but different
19 //! use openssl::memcmp::eq;
21 //! // We want to compare `a` to `b` and `c`, without giving
22 //! // away through timing analysis that `c` is more similar to `a`
24 //! let a = [0, 0, 0];
25 //! let b = [1, 1, 1];
26 //! let c = [0, 0, 1];
28 //! // These statements will execute in the same amount of time.
29 //! assert!(!eq(&a, &b));
30 //! assert!(!eq(&a, &c));
33 use openssl_macros
::corresponds
;
35 /// Returns `true` iff `a` and `b` contain the same bytes.
37 /// This operation takes an amount of time dependent on the length of the two
38 /// arrays given, but is independent of the contents of a and b.
42 /// This function will panic the current task if `a` and `b` do not have the same
47 /// To perform a constant-time comparison of two arrays of the same length but different
51 /// use openssl::memcmp::eq;
53 /// // We want to compare `a` to `b` and `c`, without giving
54 /// // away through timing analysis that `c` is more similar to `a`
56 /// let a = [0, 0, 0];
57 /// let b = [1, 1, 1];
58 /// let c = [0, 0, 1];
60 /// // These statements will execute in the same amount of time.
61 /// assert!(!eq(&a, &b));
62 /// assert!(!eq(&a, &c));
64 #[corresponds(CRYPTO_memcmp)]
65 pub fn eq(a
: &[u8], b
: &[u8]) -> bool
{
66 assert
!(a
.len() == b
.len());
69 a
.as_ptr() as *const _
,
70 b
.as_ptr() as *const _
,
83 assert
!(eq(&[], &[]));
84 assert
!(eq(&[1], &[1]));
85 assert
!(!eq(&[1, 2, 3], &[1, 2, 4]));