1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Interfaces to the operating system provided random number
14 pub use self::imp::OsRng;
16 #[cfg(all(unix, not(target_os = "ios")))]
18 use io::{IoResult, File};
21 use rand::reader::ReaderRng;
22 use result::{Ok, Err};
24 /// A random number generator that retrieves randomness straight from
25 /// the operating system. Platform sources:
27 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
29 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
30 /// service provider with the `PROV_RSA_FULL` type.
31 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
32 /// This does not block.
35 inner: ReaderRng<File>
39 /// Create a new `OsRng`.
40 pub fn new() -> IoResult<OsRng> {
41 let reader = try!(File::open(&Path::new("/dev/urandom")));
42 let reader_rng = ReaderRng::new(reader);
44 Ok(OsRng { inner: reader_rng })
49 fn next_u32(&mut self) -> u32 {
52 fn next_u64(&mut self) -> u64 {
55 fn fill_bytes(&mut self, v: &mut [u8]) {
56 self.inner.fill_bytes(v)
61 #[cfg(target_os = "ios")]
65 use collections::Collection;
72 use self::libc::{c_int, size_t};
73 use slice::MutableSlice;
75 /// A random number generator that retrieves randomness straight from
76 /// the operating system. Platform sources:
78 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
80 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
81 /// service provider with the `PROV_RSA_FULL` type.
82 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
83 /// This does not block.
85 marker: marker::NoCopy
91 static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
93 #[link(name = "Security", kind = "framework")]
95 fn SecRandomCopyBytes(rnd: *const SecRandom,
96 count: size_t, bytes: *mut u8) -> c_int;
100 /// Create a new `OsRng`.
101 pub fn new() -> IoResult<OsRng> {
102 Ok(OsRng {marker: marker::NoCopy} )
107 fn next_u32(&mut self) -> u32 {
108 let mut v = [0u8, .. 4];
110 unsafe { mem::transmute(v) }
112 fn next_u64(&mut self) -> u64 {
113 let mut v = [0u8, .. 8];
115 unsafe { mem::transmute(v) }
117 fn fill_bytes(&mut self, v: &mut [u8]) {
119 SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
122 fail!("couldn't generate random bytes: {}", os::last_os_error());
132 use core_collections::Collection;
133 use io::{IoResult, IoError};
138 use result::{Ok, Err};
139 use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
140 use self::libc::types::os::arch::extra::{LONG_PTR};
141 use slice::MutableSlice;
143 type HCRYPTPROV = LONG_PTR;
145 /// A random number generator that retrieves randomness straight from
146 /// the operating system. Platform sources:
148 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
150 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
151 /// service provider with the `PROV_RSA_FULL` type.
153 /// This does not block.
155 hcryptprov: HCRYPTPROV
158 static PROV_RSA_FULL: DWORD = 1;
159 static CRYPT_SILENT: DWORD = 64;
160 static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
162 #[allow(non_snake_case)]
164 fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
165 pszContainer: LPCSTR,
168 dwFlags: DWORD) -> BOOL;
169 fn CryptGenRandom(hProv: HCRYPTPROV,
171 pbBuffer: *mut BYTE) -> BOOL;
172 fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
176 /// Create a new `OsRng`.
177 pub fn new() -> IoResult<OsRng> {
180 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
182 CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
186 Err(IoError::last_error())
188 Ok(OsRng { hcryptprov: hcp })
194 fn next_u32(&mut self) -> u32 {
195 let mut v = [0u8, .. 4];
197 unsafe { mem::transmute(v) }
199 fn next_u64(&mut self) -> u64 {
200 let mut v = [0u8, .. 8];
202 unsafe { mem::transmute(v) }
204 fn fill_bytes(&mut self, v: &mut [u8]) {
206 CryptGenRandom(self.hcryptprov, v.len() as DWORD,
210 fail!("couldn't generate random bytes: {}", os::last_os_error());
215 impl Drop for OsRng {
218 CryptReleaseContext(self.hcryptprov, 0)
221 fail!("couldn't release context: {}", os::last_os_error());
237 let mut r = OsRng::new().unwrap();
242 let mut v = [0u8, .. 1000];
247 fn test_os_rng_tasks() {
249 let mut txs = vec!();
250 for _ in range(0u, 20) {
251 let (tx, rx) = channel();
254 // wait until all the tasks are ready to go.
257 // deschedule to attempt to interleave things as much
258 // as possible (XXX: is this a good test?)
259 let mut r = OsRng::new().unwrap();
261 let mut v = [0u8, .. 1000];
263 for _ in range(0u, 100) {
274 // start all the tasks
275 for tx in txs.iter() {