mundane/bytes.rs
1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Byte manipulation.
6//!
7//! *This module is available if Mundane is built with the `bytes` feature.*
8
9use boringssl;
10
11/// Reads cryptographically-secure random bytes.
12///
13/// This is a low-level primitive often used to construct higher-level
14/// protocols. Unless you're sure that this is what you need, you should
15/// probably be using something else. For example, all key types can be randomly
16/// generated using higher-level functions (e.g., [`EcPrivKey::generate`]),
17/// scrypt nonces are generated using the [`scrypt_generate`] function, etc.
18///
19/// [`EcPrivKey::generate`]: ::public::ec::EcPrivKey::generate
20/// [`scrypt_generate`]: ::password::scrypt::scrypt_generate
21pub fn rand(bytes: &mut [u8]) {
22 boringssl::rand_bytes(bytes);
23}
24
25/// Constant-time byte sequence equality.
26///
27/// Returns true iff the bytes at `a` and `b` are equal. Takes an
28/// amount of time dependent on length, but independent of individual
29/// byte values.
30pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
31 boringssl::crypto_memcmp(a, b)
32}
33
34#[cfg(test)]
35mod tests {
36 use super::*;
37
38 #[test]
39 fn constant_time_eq_sanity() {
40 assert!(constant_time_eq(&[], &[]));
41 assert!(!constant_time_eq(&[], &[0]));
42 assert!(constant_time_eq(&[0, 1], &[0, 1]));
43 assert!(!constant_time_eq(&[0, 1], &[0, 2]));
44 }
45}