[email protected] | 1968d977 | 2012-07-26 22:53:13 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
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] | 4a88783 | 2014-06-17 20:28:47 | [diff] [blame] | 7 | #include <nacl/nacl_random.h> |
avi | 9b6f4293 | 2015-12-26 22:15:14 | [diff] [blame] | 8 | #include <stddef.h> |
9 | #include <stdint.h> | ||||
[email protected] | 4a88783 | 2014-06-17 20:28:47 | [diff] [blame] | 10 | |
[email protected] | 1968d977 | 2012-07-26 22:53:13 | [diff] [blame] | 11 | #include "base/logging.h" |
[email protected] | 1968d977 | 2012-07-26 22:53:13 | [diff] [blame] | 12 | |
13 | namespace { | ||||
14 | |||||
[email protected] | 4a88783 | 2014-06-17 20:28:47 | [diff] [blame] | 15 | void GetRandomBytes(void* output, size_t num_bytes) { |
[email protected] | 4a88783 | 2014-06-17 20:28:47 | [diff] [blame] | 16 | char* output_ptr = static_cast<char*>(output); |
17 | while (num_bytes > 0) { | ||||
18 | size_t nread; | ||||
19 | const int error = nacl_secure_random(output_ptr, num_bytes, &nread); | ||||
20 | CHECK_EQ(error, 0); | ||||
21 | CHECK_LE(nread, num_bytes); | ||||
22 | output_ptr += nread; | ||||
23 | num_bytes -= nread; | ||||
[email protected] | 1968d977 | 2012-07-26 22:53:13 | [diff] [blame] | 24 | } |
[email protected] | 4a88783 | 2014-06-17 20:28:47 | [diff] [blame] | 25 | } |
[email protected] | 1968d977 | 2012-07-26 22:53:13 | [diff] [blame] | 26 | |
27 | } // namespace | ||||
28 | |||||
29 | namespace base { | ||||
30 | |||||
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 31 | // NOTE: This function must be cryptographically secure. http://crbug.com/140076 |
avi | 9b6f4293 | 2015-12-26 22:15:14 | [diff] [blame] | 32 | uint64_t RandUint64() { |
33 | uint64_t result; | ||||
[email protected] | 4a88783 | 2014-06-17 20:28:47 | [diff] [blame] | 34 | GetRandomBytes(&result, sizeof(result)); |
[email protected] | 1968d977 | 2012-07-26 22:53:13 | [diff] [blame] | 35 | return result; |
36 | } | ||||
37 | |||||
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 38 | void RandBytes(void* output, size_t output_length) { |
[email protected] | 4a88783 | 2014-06-17 20:28:47 | [diff] [blame] | 39 | GetRandomBytes(output, output_length); |
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 40 | } |
41 | |||||
[email protected] | 1968d977 | 2012-07-26 22:53:13 | [diff] [blame] | 42 | } // namespace base |