ring/
constant_time.rs

1// Copyright 2015-2016 Brian Smith.
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 AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS 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//! Constant-time operations.
16
17use crate::{c, error};
18
19/// Returns `Ok(())` if `a == b` and `Err(error::Unspecified)` otherwise.
20/// The comparison of `a` and `b` is done in constant time with respect to the
21/// contents of each, but NOT in constant time with respect to the lengths of
22/// `a` and `b`.
23pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
24    if a.len() != b.len() {
25        return Err(error::Unspecified);
26    }
27    let result = unsafe { GFp_memcmp(a.as_ptr(), b.as_ptr(), a.len()) };
28    match result {
29        0 => Ok(()),
30        _ => Err(error::Unspecified),
31    }
32}
33
34extern "C" {
35    fn GFp_memcmp(a: *const u8, b: *const u8, len: c::size_t) -> c::int;
36}
37
38#[cfg(test)]
39mod tests {
40    use crate::{bssl, error};
41
42    #[test]
43    fn test_constant_time() -> Result<(), error::Unspecified> {
44        extern "C" {
45            fn bssl_constant_time_test_main() -> bssl::Result;
46        }
47        Result::from(unsafe { bssl_constant_time_test_main() })
48    }
49}