Skip to content

Commit ae61549

Browse files
committed
Fix filling buffers 4 GiB or larger with OsRng::fill_bytes on Windows
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.
1 parent f872fda commit ae61549

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

src/os.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -311,13 +311,17 @@ mod imp {
311311
unsafe { mem::transmute(v) }
312312
}
313313
fn fill_bytes(&mut self, v: &mut [u8]) {
314-
let ret = unsafe {
315-
CryptGenRandom(self.hcryptprov, v.len() as DWORD,
316-
v.as_mut_ptr())
317-
};
318-
if ret == 0 {
319-
panic!("couldn't generate random bytes: {}",
320-
io::Error::last_os_error());
314+
// CryptGenRandom takes a DWORD (u32) for the length so we need to
315+
// split up the buffer.
316+
for slice in v.chunks_mut(<DWORD>::max_value() as usize) {
317+
let ret = unsafe {
318+
CryptGenRandom(self.hcryptprov, slice.len() as DWORD,
319+
slice.as_mut_ptr())
320+
};
321+
if ret == 0 {
322+
panic!("couldn't generate random bytes: {}",
323+
io::Error::last_os_error());
324+
}
321325
}
322326
}
323327
}

0 commit comments

Comments
 (0)