Skip to content

Commit 98a8a71

Browse files
committed
Auto merge of #31876 - ollie27:win_fill_bytes, r=brson
CryptGenRandom takes a DWORD (u32) for the length so it only supports writing u32::MAX bytes at a time. Casting the length from a usize caused truncation meaning the whole buffer was not always filled. cc #31841 This is the same as rust-random/rand#99. I think it's a good idea to keep the implementations in sync. r? @alexcrichton
2 parents 64b4b6d + ac3cc33 commit 98a8a71

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

src/libstd/sys/windows/rand.rs

+11-7
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,17 @@ impl Rng for OsRng {
4848
unsafe { mem::transmute(v) }
4949
}
5050
fn fill_bytes(&mut self, v: &mut [u8]) {
51-
let ret = unsafe {
52-
c::CryptGenRandom(self.hcryptprov, v.len() as c::DWORD,
53-
v.as_mut_ptr())
54-
};
55-
if ret == 0 {
56-
panic!("couldn't generate random bytes: {}",
57-
io::Error::last_os_error());
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) {
54+
let ret = unsafe {
55+
c::CryptGenRandom(self.hcryptprov, slice.len() as c::DWORD,
56+
slice.as_mut_ptr())
57+
};
58+
if ret == 0 {
59+
panic!("couldn't generate random bytes: {}",
60+
io::Error::last_os_error());
61+
}
5862
}
5963
}
6064
}

0 commit comments

Comments
 (0)