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 #[allow(non_uppercase_statics)]
92 static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
94 #[link(name = "Security", kind = "framework")]
96 fn SecRandomCopyBytes(rnd: *const SecRandom,
97 count: size_t, bytes: *mut u8) -> c_int;
101 /// Create a new `OsRng`.
102 pub fn new() -> IoResult<OsRng> {
103 Ok(OsRng {marker: marker::NoCopy} )
108 fn next_u32(&mut self) -> u32 {
109 let mut v = [0u8, .. 4];
111 unsafe { mem::transmute(v) }
113 fn next_u64(&mut self) -> u64 {
114 let mut v = [0u8, .. 8];
116 unsafe { mem::transmute(v) }
118 fn fill_bytes(&mut self, v: &mut [u8]) {
120 SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
123 panic!("couldn't generate random bytes: {}", os::last_os_error());
133 use core_collections::Collection;
134 use io::{IoResult, IoError};
139 use result::{Ok, Err};
140 use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
141 use self::libc::types::os::arch::extra::{LONG_PTR};
142 use slice::MutableSlice;
144 type HCRYPTPROV = LONG_PTR;
146 /// A random number generator that retrieves randomness straight from
147 /// the operating system. Platform sources:
149 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
151 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
152 /// service provider with the `PROV_RSA_FULL` type.
154 /// This does not block.
156 hcryptprov: HCRYPTPROV
159 static PROV_RSA_FULL: DWORD = 1;
160 static CRYPT_SILENT: DWORD = 64;
161 static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
163 #[allow(non_snake_case)]
165 fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
166 pszContainer: LPCSTR,
169 dwFlags: DWORD) -> BOOL;
170 fn CryptGenRandom(hProv: HCRYPTPROV,
172 pbBuffer: *mut BYTE) -> BOOL;
173 fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
177 /// Create a new `OsRng`.
178 pub fn new() -> IoResult<OsRng> {
181 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
183 CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
187 Err(IoError::last_error())
189 Ok(OsRng { hcryptprov: hcp })
195 fn next_u32(&mut self) -> u32 {
196 let mut v = [0u8, .. 4];
198 unsafe { mem::transmute(v) }
200 fn next_u64(&mut self) -> u64 {
201 let mut v = [0u8, .. 8];
203 unsafe { mem::transmute(v) }
205 fn fill_bytes(&mut self, v: &mut [u8]) {
207 CryptGenRandom(self.hcryptprov, v.len() as DWORD,
211 panic!("couldn't generate random bytes: {}", os::last_os_error());
216 impl Drop for OsRng {
219 CryptReleaseContext(self.hcryptprov, 0)
222 panic!("couldn't release context: {}", os::last_os_error());
238 let mut r = OsRng::new().unwrap();
243 let mut v = [0u8, .. 1000];
248 fn test_os_rng_tasks() {
250 let mut txs = vec!();
251 for _ in range(0u, 20) {
252 let (tx, rx) = channel();
255 // wait until all the tasks are ready to go.
258 // deschedule to attempt to interleave things as much
259 // as possible (XXX: is this a good test?)
260 let mut r = OsRng::new().unwrap();
262 let mut v = [0u8, .. 1000];
264 for _ in range(0u, 100) {
275 // start all the tasks
276 for tx in txs.iter() {