blob: 76a5dabdc6a22cdbec58a61c66a2caa3f7f80a5f [file] [log] [blame]
Vitaly Bukacbed2062015-08-17 12:54:05 -07001// 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
7#include <errno.h>
8#include <fcntl.h>
9#include <unistd.h>
10
Vitaly Bukacbed2062015-08-17 12:54:05 -070011#include "base/logging.h"
Vitaly Buka8750b272015-08-18 18:39:08 -070012#include "base/posix/eintr_wrapper.h"
Vitaly Bukacbed2062015-08-17 12:54:05 -070013
14namespace {
15
Vitaly Bukacbed2062015-08-17 12:54:05 -070016class URandomFd {
17 public:
18 URandomFd() : fd_(open("/dev/urandom", O_RDONLY)) {
19 DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno;
20 }
21
22 ~URandomFd() { close(fd_); }
23
24 int fd() const { return fd_; }
25
26 private:
27 const int fd_;
28};
29
Vitaly Buka8750b272015-08-18 18:39:08 -070030bool ReadFromFD(int fd, char* buffer, size_t bytes) {
31 size_t total_read = 0;
32 while (total_read < bytes) {
33 ssize_t bytes_read =
34 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
35 if (bytes_read <= 0)
36 break;
37 total_read += bytes_read;
38 }
39 return total_read == bytes;
40}
Vitaly Bukacbed2062015-08-17 12:54:05 -070041
42} // namespace
43
44namespace base {
45
46// NOTE: This function must be cryptographically secure. http://crbug.com/140076
47uint64 RandUint64() {
48 uint64 number;
49 RandBytes(&number, sizeof(number));
50 return number;
51}
52
53void RandBytes(void* output, size_t output_length) {
Vitaly Buka8750b272015-08-18 18:39:08 -070054 URandomFd urandom_fd;
Vitaly Bukacbed2062015-08-17 12:54:05 -070055 const bool success =
Vitaly Buka8750b272015-08-18 18:39:08 -070056 ReadFromFD(urandom_fd.fd(), static_cast<char*>(output), output_length);
Vitaly Bukacbed2062015-08-17 12:54:05 -070057 CHECK(success);
58}
59
Vitaly Bukacbed2062015-08-17 12:54:05 -070060} // namespace base