[email protected] | 9b20578 | 2012-08-02 20:22:25 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
3 | // found in the LICENSE file. | ||||
4 | |||||
5 | #include "base/rand_util.h" | ||||
6 | |||||
[email protected] | 8c37218a | 2014-01-24 00:01:14 | [diff] [blame] | 7 | #include <windows.h> |
avi | 9b6f4293 | 2015-12-26 22:15:14 | [diff] [blame] | 8 | #include <stddef.h> |
9 | #include <stdint.h> | ||||
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 10 | |
[email protected] | 8c37218a | 2014-01-24 00:01:14 | [diff] [blame] | 11 | // #define needed to link in RtlGenRandom(), a.k.a. SystemFunction036. See the |
12 | // "Community Additions" comment on MSDN here: | ||||
13 | // http://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx | ||||
14 | #define SystemFunction036 NTAPI SystemFunction036 | ||||
15 | #include <NTSecAPI.h> | ||||
16 | #undef SystemFunction036 | ||||
17 | |||||
18 | #include <algorithm> | ||||
19 | #include <limits> | ||||
20 | |||||
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 21 | #include "base/logging.h" |
22 | |||||
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 23 | namespace base { |
24 | |||||
[email protected] | 9b20578 | 2012-08-02 20:22:25 | [diff] [blame] | 25 | // NOTE: This function must be cryptographically secure. http://crbug.com/140076 |
avi | 9b6f4293 | 2015-12-26 22:15:14 | [diff] [blame] | 26 | uint64_t RandUint64() { |
27 | uint64_t number; | ||||
[email protected] | 8c37218a | 2014-01-24 00:01:14 | [diff] [blame] | 28 | RandBytes(&number, sizeof(number)); |
29 | return number; | ||||
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 30 | } |
31 | |||||
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 32 | void RandBytes(void* output, size_t output_length) { |
[email protected] | 8c37218a | 2014-01-24 00:01:14 | [diff] [blame] | 33 | char* output_ptr = static_cast<char*>(output); |
34 | while (output_length > 0) { | ||||
35 | const ULONG output_bytes_this_pass = static_cast<ULONG>(std::min( | ||||
36 | output_length, static_cast<size_t>(std::numeric_limits<ULONG>::max()))); | ||||
37 | const bool success = | ||||
38 | RtlGenRandom(output_ptr, output_bytes_this_pass) != FALSE; | ||||
39 | CHECK(success); | ||||
40 | output_length -= output_bytes_this_pass; | ||||
41 | output_ptr += output_bytes_this_pass; | ||||
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 42 | } |
43 | } | ||||
44 | |||||
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 45 | } // namespace base |