Debian Codegraph @

.cargo/vendor/getrandom/src/backends/windows.rs

raw
1 //! Implementation for Windows 10 and later
2 //!
3 //! On Windows 10 and later, ProcessPrng "is the primary interface to the
4 //! user-mode per-processor PRNGs" and only requires bcryptprimitives.dll,
5 //! making it a better option than the other Windows RNG APIs:
6 //! - BCryptGenRandom: https://learn.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom
7 //! - Requires bcrypt.dll (which loads bcryptprimitives.dll anyway)
8 //! - Can cause crashes/hangs as BCrypt accesses the Windows Registry:
9 //! https://github.com/rust-lang/rust/issues/99341
10 //! - Causes issues inside sandboxed code:
11 //! https://issues.chromium.org/issues/40277768
12 //! - CryptGenRandom: https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptgenrandom
13 //! - Deprecated and not available on UWP targets
14 //! - Requires advapi32.lib/advapi32.dll (in addition to bcryptprimitives.dll)
15 //! - Thin wrapper around ProcessPrng
16 //! - RtlGenRandom: https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom
17 //! - Deprecated and not available on UWP targets
18 //! - Requires advapi32.dll (in addition to bcryptprimitives.dll)
19 //! - Requires using name "SystemFunction036"
20 //! - Thin wrapper around ProcessPrng
21 //!
22 //! For more information see the Windows RNG Whitepaper: https://aka.ms/win10rng
23 use crate::Error;
24 use core::mem::MaybeUninit;
25
26 pub use crate::util::{inner_u32, inner_u64};
27
28 // Binding to the Windows.Win32.Security.Cryptography.ProcessPrng API. As
29 // bcryptprimitives.dll lacks an import library, we use "raw-dylib". This
30 // was added in Rust 1.65 for x86_64/aarch64 and in Rust 1.71 for x86.
31 // We don't need MSRV 1.71, as we only use this backend on Rust 1.78 and later.
32 #[cfg_attr(
33 target_arch = "x86",
34 link(
35 name = "bcryptprimitives",
36 kind = "raw-dylib",
37 import_name_type = "undecorated"
38 )
39 )]
40 #[cfg_attr(
41 not(target_arch = "x86"),
42 link(name = "bcryptprimitives", kind = "raw-dylib")
43 )]
44 extern "system" {
45 fn ProcessPrng(pbdata: *mut u8, cbdata: usize) -> BOOL;
46 }
47 #[allow(clippy::upper_case_acronyms, clippy::incompatible_msrv)]
48 type BOOL = core::ffi::c_int; // MSRV 1.64, similarly OK for this backend.
49 const TRUE: BOOL = 1;
50
51 #[inline]
52 pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
53 let result = unsafe { ProcessPrng(dest.as_mut_ptr().cast::<u8>(), dest.len()) };
54 // Since Windows 10, calls to the user-mode RNG are guaranteed to never
55 // fail during runtime (rare windows W); `ProcessPrng` will only ever
56 // return 1 (which is how windows represents TRUE).
57 // See the bottom of page 6 of the aforementioned Windows RNG
58 // whitepaper for more information.
59 debug_assert!(result == TRUE);
60 Ok(())
61 }