2 * Copyright 2015 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/Random.h>
26 #include <glog/logging.h>
27 #include <folly/File.h>
28 #include <folly/FileUtil.h>
31 # include <wincrypt.h>
38 void readRandomDevice(void* data, size_t size) {
40 static std::once_flag flag;
41 static HCRYPTPROV cryptoProv;
42 std::call_once(flag, [&] {
43 PCHECK(CryptAcquireContext(&cryptoProv, nullptr, nullptr,
46 CHECK(size <= std::numeric_limits<DWORD>::max());
47 PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data));
49 // Keep the random device open for the duration of the program.
50 static int randomFd = ::open("/dev/urandom", O_RDONLY);
51 PCHECK(randomFd >= 0);
52 auto bytesRead = readFull(randomFd, data, size);
53 PCHECK(bytesRead >= 0 && size_t(bytesRead) == size);
57 class BufferedRandomDevice {
59 static constexpr size_t kDefaultBufferSize = 128;
61 explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
63 void get(void* data, size_t size) {
64 if (LIKELY(size <= remaining())) {
65 memcpy(data, ptr_, size);
68 getSlow(static_cast<unsigned char*>(data), size);
73 void getSlow(unsigned char* data, size_t size);
75 inline size_t remaining() const {
76 return buffer_.get() + bufferSize_ - ptr_;
79 const size_t bufferSize_;
80 std::unique_ptr<unsigned char[]> buffer_;
84 BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
85 : bufferSize_(bufferSize),
86 buffer_(new unsigned char[bufferSize]),
87 ptr_(buffer_.get() + bufferSize) { // refill on first use
90 void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
91 DCHECK_GT(size, remaining());
92 if (size >= bufferSize_) {
93 // Just read directly.
94 readRandomDevice(data, size);
98 size_t copied = remaining();
99 memcpy(data, ptr_, copied);
104 readRandomDevice(buffer_.get(), bufferSize_);
105 ptr_ = buffer_.get();
107 memcpy(data, ptr_, size);
114 void Random::secureRandom(void* data, size_t size) {
115 static ThreadLocal<BufferedRandomDevice> bufferedRandomDevice;
116 bufferedRandomDevice->get(data, size);
119 ThreadLocalPRNG::ThreadLocalPRNG() {
120 static folly::ThreadLocal<ThreadLocalPRNG::LocalInstancePRNG> localInstance;
121 local_ = localInstance.get();
124 class ThreadLocalPRNG::LocalInstancePRNG {
126 LocalInstancePRNG() : rng(Random::create()) { }
128 Random::DefaultGenerator rng;
131 uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) {