blob: 22fdd4da72c83f9e8c189d6467c82d730f5c7f0f [file] [log] [blame]
[email protected]9b205782012-08-02 20:22:251// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]05f9b682008-09-29 22:18:012// 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]8c37218a2014-01-24 00:01:147#include <windows.h>
avi9b6f42932015-12-26 22:15:148#include <stddef.h>
9#include <stdint.h>
[email protected]05f9b682008-09-29 22:18:0110
[email protected]8c37218a2014-01-24 00:01:1411// #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]05f9b682008-09-29 22:18:0121#include "base/logging.h"
22
[email protected]05f9b682008-09-29 22:18:0123namespace base {
24
[email protected]9b205782012-08-02 20:22:2525// NOTE: This function must be cryptographically secure. http://crbug.com/140076
avi9b6f42932015-12-26 22:15:1426uint64_t RandUint64() {
27 uint64_t number;
[email protected]8c37218a2014-01-24 00:01:1428 RandBytes(&number, sizeof(number));
29 return number;
[email protected]05f9b682008-09-29 22:18:0130}
31
[email protected]c910c5a2014-01-23 02:14:2832void RandBytes(void* output, size_t output_length) {
[email protected]8c37218a2014-01-24 00:01:1433 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]c910c5a2014-01-23 02:14:2842 }
43}
44
[email protected]05f9b682008-09-29 22:18:0145} // namespace base