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 // BCryptGenRandom was introduced in Windows Vista
28 let ret = unsafe {
29 BCryptGenRandom(
30 ptr::null_mut(),
31 chunk.as_mut_ptr(),
32 chunk.len() as u32,
33 BCRYPT_USE_SYSTEM_PREFERRED_RNG,
34 )
35 };
36 // NTSTATUS codes use the two highest bits for severity status.
37 if ret >> 30 == 0b11 {
38 // We zeroize the highest bit, so the error code will reside
39 // inside the range designated for OS codes.
40 let code = ret ^ (1 << 31);
41 // SAFETY: the second highest bit is always equal to one,
42 // so it's impossible to get zero. Unfortunately the type
43 // system does not have a way to express this yet.
44 let code = unsafe { NonZeroU32::new_unchecked(code) };
45 return Err(Error::from(code));
46 }
47 }
48 Ok(())
49 }
50