blob: b771dc44547dbce7f3b99058cab0c6bce4c43fe1 [file] [log] [blame]
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001// 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
Torne (Richard Coles)f8ee7882014-06-20 14:52:04 +01007#include <nacl/nacl_random.h>
8
Torne (Richard Coles)58218062012-11-14 11:43:16 +00009#include "base/basictypes.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000010#include "base/logging.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000011
12namespace {
13
Torne (Richard Coles)f8ee7882014-06-20 14:52:04 +010014void GetRandomBytes(void* output, size_t num_bytes) {
Torne (Richard Coles)f8ee7882014-06-20 14:52:04 +010015 char* output_ptr = static_cast<char*>(output);
16 while (num_bytes > 0) {
17 size_t nread;
18 const int error = nacl_secure_random(output_ptr, num_bytes, &nread);
19 CHECK_EQ(error, 0);
20 CHECK_LE(nread, num_bytes);
21 output_ptr += nread;
22 num_bytes -= nread;
Torne (Richard Coles)58218062012-11-14 11:43:16 +000023 }
Torne (Richard Coles)f8ee7882014-06-20 14:52:04 +010024}
Torne (Richard Coles)58218062012-11-14 11:43:16 +000025
26} // namespace
27
28namespace base {
29
Torne (Richard Coles)5d1f7b12014-02-21 12:16:55 +000030// NOTE: This function must be cryptographically secure. http://crbug.com/140076
Torne (Richard Coles)58218062012-11-14 11:43:16 +000031uint64 RandUint64() {
32 uint64 result;
Torne (Richard Coles)f8ee7882014-06-20 14:52:04 +010033 GetRandomBytes(&result, sizeof(result));
Torne (Richard Coles)58218062012-11-14 11:43:16 +000034 return result;
35}
36
Torne (Richard Coles)5d1f7b12014-02-21 12:16:55 +000037void RandBytes(void* output, size_t output_length) {
Torne (Richard Coles)f8ee7882014-06-20 14:52:04 +010038 GetRandomBytes(output, output_length);
Torne (Richard Coles)5d1f7b12014-02-21 12:16:55 +000039}
40
Torne (Richard Coles)58218062012-11-14 11:43:16 +000041} // namespace base