1 // Copyright 2013-2015 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.
18 hcryptprov
: c
::HCRYPTPROV
22 /// Create a new `OsRng`.
23 pub fn new() -> io
::Result
<OsRng
> {
26 c
::CryptAcquireContextA(&mut hcp
, 0 as c
::LPCSTR
, 0 as c
::LPCSTR
,
28 c
::CRYPT_VERIFYCONTEXT
| c
::CRYPT_SILENT
)
32 Err(io
::Error
::last_os_error())
34 Ok(OsRng { hcryptprov: hcp }
)
40 fn next_u32(&mut self) -> u32 {
42 self.fill_bytes(&mut v
);
43 unsafe { mem::transmute(v) }
45 fn next_u64(&mut self) -> u64 {
47 self.fill_bytes(&mut v
);
48 unsafe { mem::transmute(v) }
50 fn fill_bytes(&mut self, v
: &mut [u8]) {
51 // CryptGenRandom takes a DWORD (u32) for the length so we need to
52 // split up the buffer.
53 for slice
in v
.chunks_mut(<c
::DWORD
>::max_value() as usize) {
55 c
::CryptGenRandom(self.hcryptprov
, slice
.len() as c
::DWORD
,
59 panic
!("couldn't generate random bytes: {}",
60 io
::Error
::last_os_error());
69 c
::CryptReleaseContext(self.hcryptprov
, 0)
72 panic
!("couldn't release context: {}",
73 io
::Error
::last_os_error());