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.
5 #include "base/rand_util.h"
11 #include "base/files/file_util.h"
12 #include "base/lazy_instance.h"
13 #include "base/logging.h"
17 // We keep the file descriptor for /dev/urandom around so we don't need to
18 // reopen it (which is expensive), and since we may not even be able to reopen
19 // it if we are later put in a sandbox. This class wraps the file descriptor so
20 // we can use LazyInstance to handle opening it on the first access.
23 URandomFd() : fd_(open("/dev/urandom", O_RDONLY)) {
24 DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno;
27 ~URandomFd() { close(fd_); }
29 int fd() const { return fd_; }
35 base::LazyInstance<URandomFd>::Leaky g_urandom_fd = LAZY_INSTANCE_INITIALIZER;
41 // NOTE: This function must be cryptographically secure. http://crbug.com/140076
44 RandBytes(&number, sizeof(number));
48 void RandBytes(void* output, size_t output_length) {
49 const int urandom_fd = g_urandom_fd.Pointer()->fd();
51 ReadFromFD(urandom_fd, static_cast<char*>(output), output_length);
55 int GetUrandomFD(void) {
56 return g_urandom_fd.Pointer()->fd();