rc_crypto/
constant_time.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5// This file contains code that was copied from the ring crate which is under
6// the ISC license, reproduced below:
7
8// Copyright 2015-2017 Brian Smith.
9
10// Permission to use, copy, modify, and/or distribute this software for any
11// purpose with or without fee is hereby granted, provided that the above
12// copyright notice and this permission notice appear in all copies.
13
14// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
15// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
17// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
19// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
20// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21
22use crate::error::*;
23
24/// Returns `Ok(())` if `a == b` and `Error` otherwise.
25/// The comparison of `a` and `b` is done in constant time with respect to the
26/// contents of each, but NOT in constant time with respect to the lengths of
27/// `a` and `b`.
28pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<()> {
29    if nss::secport::secure_memcmp(a, b)? {
30        Ok(())
31    } else {
32        Err(ErrorKind::InternalError.into())
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39    use nss::ensure_initialized;
40
41    #[test]
42    fn does_compare() {
43        ensure_initialized();
44        assert!(verify_slices_are_equal(b"bobo", b"bobo").is_ok());
45        assert!(verify_slices_are_equal(b"bobo", b"obob").is_err());
46        assert!(verify_slices_are_equal(b"bobo", b"notbobo").is_err());
47    }
48}