| // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| #include "base/rand_util.h" |
| #include "base/logging.h" |
| #include "base/posix/eintr_wrapper.h" |
| URandomFd() : fd_(open("/dev/urandom", O_RDONLY)) { |
| DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno; |
| ~URandomFd() { close(fd_); } |
| int fd() const { return fd_; } |
| bool ReadFromFD(int fd, char* buffer, size_t bytes) { |
| while (total_read < bytes) { |
| HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read)); |
| total_read += bytes_read; |
| return total_read == bytes; |
| // NOTE: This function must be cryptographically secure. http://crbug.com/140076 |
| RandBytes(&number, sizeof(number)); |
| void RandBytes(void* output, size_t output_length) { |
| ReadFromFD(urandom_fd.fd(), static_cast<char*>(output), output_length); |