2 * Copyright 2016 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>
24 #include <glog/logging.h>
25 #include <folly/CallOnce.h>
26 #include <folly/File.h>
27 #include <folly/FileUtil.h>
28 #include <folly/ThreadLocal.h>
29 #include <folly/portability/SysTime.h>
30 #include <folly/portability/Unistd.h>
33 # include <wincrypt.h>
40 void readRandomDevice(void* data, size_t size) {
42 static folly::once_flag flag;
43 static HCRYPTPROV cryptoProv;
44 folly::call_once(flag, [&] {
45 if (!CryptAcquireContext(&cryptoProv, nullptr, nullptr, PROV_RSA_FULL, 0)) {
46 if (GetLastError() == NTE_BAD_KEYSET) {
47 // Mostly likely cause of this is that no key container
48 // exists yet, so try to create one.
49 PCHECK(CryptAcquireContext(
50 &cryptoProv, nullptr, nullptr, PROV_RSA_FULL, CRYPT_NEWKEYSET));
52 LOG(FATAL) << "Failed to acquire the default crypto context.";
56 CHECK(size <= std::numeric_limits<DWORD>::max());
57 PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data));
59 // Keep the random device open for the duration of the program.
60 static int randomFd = ::open("/dev/urandom", O_RDONLY);
61 PCHECK(randomFd >= 0);
62 auto bytesRead = readFull(randomFd, data, size);
63 PCHECK(bytesRead >= 0 && size_t(bytesRead) == size);
67 class BufferedRandomDevice {
69 static constexpr size_t kDefaultBufferSize = 128;
71 explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
73 void get(void* data, size_t size) {
74 if (LIKELY(size <= remaining())) {
75 memcpy(data, ptr_, size);
78 getSlow(static_cast<unsigned char*>(data), size);
83 void getSlow(unsigned char* data, size_t size);
85 inline size_t remaining() const {
86 return buffer_.get() + bufferSize_ - ptr_;
89 const size_t bufferSize_;
90 std::unique_ptr<unsigned char[]> buffer_;
94 BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
95 : bufferSize_(bufferSize),
96 buffer_(new unsigned char[bufferSize]),
97 ptr_(buffer_.get() + bufferSize) { // refill on first use
100 void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
101 DCHECK_GT(size, remaining());
102 if (size >= bufferSize_) {
103 // Just read directly.
104 readRandomDevice(data, size);
108 size_t copied = remaining();
109 memcpy(data, ptr_, copied);
114 readRandomDevice(buffer_.get(), bufferSize_);
115 ptr_ = buffer_.get();
117 memcpy(data, ptr_, size);
124 void Random::secureRandom(void* data, size_t size) {
125 static ThreadLocal<BufferedRandomDevice> bufferedRandomDevice;
126 bufferedRandomDevice->get(data, size);
129 class ThreadLocalPRNG::LocalInstancePRNG {
131 LocalInstancePRNG() : rng(Random::create()) { }
133 Random::DefaultGenerator rng;
136 ThreadLocalPRNG::ThreadLocalPRNG() {
137 static folly::ThreadLocal<ThreadLocalPRNG::LocalInstancePRNG> localInstance;
138 local_ = localInstance.get();
141 uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) {