]> git.lizzy.rs Git - rust.git/commitdiff
rand: Fix filling buffers 4 GiB or larger with OsRng::fill_bytes on Windows
authorOliver Middleton <olliemail27@gmail.com>
Thu, 25 Feb 2016 01:35:41 +0000 (01:35 +0000)
committerOliver Middleton <olliemail27@gmail.com>
Thu, 25 Feb 2016 01:35:41 +0000 (01:35 +0000)
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.

src/libstd/sys/windows/rand.rs

index fdd260b6e28844959fed6fd2860fde4a4194c410..10e3d45f9d5eb8813bbfa72b59661a7c93e5f732 100644 (file)
@@ -48,13 +48,17 @@ fn next_u64(&mut self) -> u64 {
         unsafe { mem::transmute(v) }
     }
     fn fill_bytes(&mut self, v: &mut [u8]) {
-        let ret = unsafe {
-            c::CryptGenRandom(self.hcryptprov, v.len() as c::DWORD,
-                              v.as_mut_ptr())
-        };
-        if ret == 0 {
-            panic!("couldn't generate random bytes: {}",
-                   io::Error::last_os_error());
+        // CryptGenRandom takes a DWORD (u32) for the length so we need to
+        // split up the buffer.
+        for slice in v.chunks_mut(<c::DWORD>::max_value() as usize) {
+            let ret = unsafe {
+                c::CryptGenRandom(self.hcryptprov, slice.len() as c::DWORD,
+                                  slice.as_mut_ptr())
+            };
+            if ret == 0 {
+                panic!("couldn't generate random bytes: {}",
+                       io::Error::last_os_error());
+            }
         }
     }
 }