rc_crypto/
rand.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/// Fill a buffer with cryptographically secure pseudo-random data.
25pub fn fill(dest: &mut [u8]) -> Result<()> {
26    Ok(nss::pk11::slot::generate_random(dest)?)
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32    use nss::ensure_initialized;
33
34    #[test]
35    fn random_fill() {
36        ensure_initialized();
37
38        let mut out = vec![0u8; 64];
39        assert!(fill(&mut out).is_ok());
40        // This check could *in theory* fail if we randomly generate all zeroes
41        // but we're treating that probability as negligible in practice.
42        assert_ne!(out, vec![0u8; 64]);
43
44        let mut out2 = vec![0u8; 64];
45        assert!(fill(&mut out2).is_ok());
46        assert_ne!(out, vec![0u8; 64]);
47        assert_ne!(out2, out);
48    }
49
50    #[test]
51    fn random_fill_empty() {
52        ensure_initialized();
53
54        let mut out = vec![0u8; 0];
55        assert!(fill(&mut out).is_ok());
56        assert_eq!(out, vec![0u8; 0]);
57    }
58
59    #[test]
60    fn random_fill_oddly_sized_arrays() {
61        ensure_initialized();
62
63        let sizes: [usize; 4] = [61, 63, 65, 67];
64        for size in &sizes {
65            let mut out = vec![0u8; *size];
66            assert!(fill(&mut out).is_ok());
67            assert_ne!(out, vec![0u8; *size]);
68        }
69    }
70
71    #[test]
72    fn random_fill_rejects_attempts_to_fill_gigantic_arrays() {
73        ensure_initialized();
74
75        let max_size: usize = i32::MAX as usize;
76        let mut out = vec![0u8; max_size + 1];
77        assert!(fill(&mut out).is_err());
78    }
79}