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>
29 #include <folly/ThreadLocal.h>
32 # include <wincrypt.h>
39 void readRandomDevice(void* data, size_t size) {
41 static std::once_flag flag;
42 static HCRYPTPROV cryptoProv;
43 std::call_once(flag, [&] {
44 PCHECK(CryptAcquireContext(&cryptoProv, nullptr, nullptr,
47 CHECK(size <= std::numeric_limits<DWORD>::max());
48 PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data));
50 // Keep the random device open for the duration of the program.
51 static int randomFd = ::open("/dev/urandom", O_RDONLY);
52 PCHECK(randomFd >= 0);
53 auto bytesRead = readFull(randomFd, data, size);
54 PCHECK(bytesRead >= 0 && size_t(bytesRead) == size);
58 class BufferedRandomDevice {
60 static constexpr size_t kDefaultBufferSize = 128;
62 explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
64 void get(void* data, size_t size) {
65 if (LIKELY(size <= remaining())) {
66 memcpy(data, ptr_, size);
69 getSlow(static_cast<unsigned char*>(data), size);
74 void getSlow(unsigned char* data, size_t size);
76 inline size_t remaining() const {
77 return buffer_.get() + bufferSize_ - ptr_;
80 const size_t bufferSize_;
81 std::unique_ptr<unsigned char[]> buffer_;
85 BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
86 : bufferSize_(bufferSize),
87 buffer_(new unsigned char[bufferSize]),
88 ptr_(buffer_.get() + bufferSize) { // refill on first use
91 void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
92 DCHECK_GT(size, remaining());
93 if (size >= bufferSize_) {
94 // Just read directly.
95 readRandomDevice(data, size);
99 size_t copied = remaining();
100 memcpy(data, ptr_, copied);
105 readRandomDevice(buffer_.get(), bufferSize_);
106 ptr_ = buffer_.get();
108 memcpy(data, ptr_, size);
115 void Random::secureRandom(void* data, size_t size) {
116 static ThreadLocal<BufferedRandomDevice> bufferedRandomDevice;
117 bufferedRandomDevice->get(data, size);
120 class ThreadLocalPRNG::LocalInstancePRNG {
122 LocalInstancePRNG() : rng(Random::create()) { }
124 Random::DefaultGenerator rng;
127 ThreadLocalPRNG::ThreadLocalPRNG() {
128 static folly::ThreadLocal<ThreadLocalPRNG::LocalInstancePRNG> localInstance;
129 local_ = localInstance.get();
132 uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) {