aws_lc_rs/
constant_time.rs

1// Copyright 2015-2022 Brian Smith.
2// SPDX-License-Identifier: ISC
3// Modifications copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0 OR ISC
5
6//! Constant-time operations.
7
8use crate::aws_lc::CRYPTO_memcmp;
9use crate::error;
10
11/// Returns `Ok(())` if `a == b` and `Err(error::Unspecified)` otherwise.
12///
13/// The comparison of `a` and `b` is done in constant time with respect to the
14/// contents of each, but NOT in constant time with respect to the lengths of
15/// `a` and `b`.
16///
17/// # Errors
18/// `error::Unspecified` when `a` and `b` differ.
19#[inline]
20pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
21    if a.len() != b.len() {
22        return Err(error::Unspecified);
23    }
24    let result = unsafe { CRYPTO_memcmp(a.as_ptr().cast(), b.as_ptr().cast(), a.len()) };
25    match result {
26        0 => Ok(()),
27        _ => Err(error::Unspecified),
28    }
29}