1 //! # Random key generation
3 //! This module wraps the RNG provided by the OS. There are a few different
4 //! ways to interface with the OS RNG so it's worth exploring each of the options.
5 //! Note that at the time of writing these all go through the (undocumented)
6 //! `bcryptPrimitives.dll` but they use different route to get there.
8 //! Originally we were using [`RtlGenRandom`], however that function is
9 //! deprecated and warns it "may be altered or unavailable in subsequent versions".
11 //! So we switched to [`BCryptGenRandom`] with the `BCRYPT_USE_SYSTEM_PREFERRED_RNG`
12 //! flag to query and find the system configured RNG. However, this change caused a small
13 //! but significant number of users to experience panics caused by a failure of
14 //! this function. See [#94098].
16 //! The current version falls back to using `BCryptOpenAlgorithmProvider` if
17 //! `BCRYPT_USE_SYSTEM_PREFERRED_RNG` fails for any reason.
19 //! [#94098]: https://github.com/rust-lang/rust/issues/94098
20 //! [`RtlGenRandom`]: https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom
21 //! [`BCryptGenRandom`]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom
26 /// Generates high quality secure random keys for use by [`HashMap`].
28 /// This is used to seed the default [`RandomState`].
30 /// [`HashMap`]: crate::collections::HashMap
31 /// [`RandomState`]: crate::collections::hash_map::RandomState
32 pub fn hashmap_random_keys() -> (u64, u64) {
33 Rng::SYSTEM.gen_random_keys().unwrap_or_else(fallback_rng)
37 algorithm: c::BCRYPT_ALG_HANDLE,
41 const SYSTEM: Self = unsafe { Self::new(ptr::null_mut(), c::BCRYPT_USE_SYSTEM_PREFERRED_RNG) };
43 /// Create the RNG from an existing algorithm handle.
47 /// The handle must either be null or a valid algorithm handle.
48 const unsafe fn new(algorithm: c::BCRYPT_ALG_HANDLE, flags: u32) -> Self {
49 Self { algorithm, flags }
52 /// Open a handle to the RNG algorithm.
53 fn open() -> Result<Self, c::NTSTATUS> {
54 use crate::sync::atomic::AtomicPtr;
55 use crate::sync::atomic::Ordering::{Acquire, Release};
57 // An atomic is used so we don't need to reopen the handle every time.
58 static HANDLE: AtomicPtr<crate::ffi::c_void> = AtomicPtr::new(ptr::null_mut());
60 let mut handle = HANDLE.load(Acquire);
63 c::BCryptOpenAlgorithmProvider(
65 c::BCRYPT_RNG_ALGORITHM.as_ptr(),
70 if c::nt_success(status) {
71 // If another thread opens a handle first then use that handle instead.
72 let result = HANDLE.compare_exchange(ptr::null_mut(), handle, Release, Acquire);
73 if let Err(previous_handle) = result {
74 // Close our handle and return the previous one.
75 unsafe { c::BCryptCloseAlgorithmProvider(handle, 0) };
76 handle = previous_handle;
78 Ok(unsafe { Self::new(handle, 0) })
83 Ok(unsafe { Self::new(handle, 0) })
87 fn gen_random_keys(self) -> Result<(u64, u64), c::NTSTATUS> {
90 let size = mem::size_of_val(&v).try_into().unwrap();
91 c::BCryptGenRandom(self.algorithm, ptr::addr_of_mut!(v).cast(), size, self.flags)
93 if c::nt_success(status) { Ok(v) } else { Err(status) }
97 /// Generate random numbers using the fallback RNG function
99 fn fallback_rng(rng_status: c::NTSTATUS) -> (u64, u64) {
100 match Rng::open().and_then(|rng| rng.gen_random_keys()) {
103 panic!("RNG broken: {rng_status:#x}, fallback RNG broken: {status:#x}")