• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018 Developers of the Rand project.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8 
9 use crate::Error;
10 use core::{ffi::c_void, num::NonZeroU32, ptr};
11 
12 const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x00000002;
13 
14 #[link(name = "bcrypt")]
15 extern "system" {
BCryptGenRandom( hAlgorithm: *mut c_void, pBuffer: *mut u8, cbBuffer: u32, dwFlags: u32, ) -> u3216     fn BCryptGenRandom(
17         hAlgorithm: *mut c_void,
18         pBuffer: *mut u8,
19         cbBuffer: u32,
20         dwFlags: u32,
21     ) -> u32;
22 }
23 
getrandom_inner(dest: &mut [u8]) -> Result<(), Error>24 pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
25     // Prevent overflow of u32
26     for chunk in dest.chunks_mut(u32::max_value() as usize) {
27         let ret = unsafe {
28             BCryptGenRandom(
29                 ptr::null_mut(),
30                 chunk.as_mut_ptr(),
31                 chunk.len() as u32,
32                 BCRYPT_USE_SYSTEM_PREFERRED_RNG,
33             )
34         };
35         // NTSTATUS codes use the two highest bits for severity status.
36         if ret >> 30 == 0b11 {
37             // We zeroize the highest bit, so the error code will reside
38             // inside the range designated for OS codes.
39             let code = ret ^ (1 << 31);
40             // SAFETY: the second highest bit is always equal to one,
41             // so it's impossible to get zero. Unfortunately the type
42             // system does not have a way to express this yet.
43             let code = unsafe { NonZeroU32::new_unchecked(code) };
44             return Err(Error::from(code));
45         }
46     }
47     Ok(())
48 }
49