Commit 9af38044 authored by Orvid King's avatar Orvid King Committed by facebook-github-bot-1

Implement Random.cpp for MSVC

Summary: This uses `<random>` to implement it, because there is no `/dev/urandom` on Windows.
Closes #250

Reviewed By: @yfeldblum

Differential Revision: D2282887

Pulled By: @sgolemon
parent 750586e0
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
#include <atomic> #include <atomic>
#include <unistd.h> #include <unistd.h>
#include <sys/time.h> #include <sys/time.h>
#include <mutex>
#include <random> #include <random>
#include <array> #include <array>
...@@ -26,16 +27,31 @@ ...@@ -26,16 +27,31 @@
#include <folly/File.h> #include <folly/File.h>
#include <folly/FileUtil.h> #include <folly/FileUtil.h>
#ifdef _MSC_VER
# include <wincrypt.h>
#endif
namespace folly { namespace folly {
namespace { namespace {
void readRandomDevice(void* data, size_t size) { void readRandomDevice(void* data, size_t size) {
#ifdef _MSC_VER
static std::once_flag flag;
static HCRYPTPROV cryptoProv;
std::call_once(flag, [&] {
PCHECK(CryptAcquireContext(&cryptoProv, nullptr, nullptr,
PROV_RSA_FULL, 0));
});
CHECK(size <= std::numeric_limits<DWORD>::max());
PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data));
#else
// Keep the random device open for the duration of the program. // Keep the random device open for the duration of the program.
static int randomFd = ::open("/dev/urandom", O_RDONLY); static int randomFd = ::open("/dev/urandom", O_RDONLY);
PCHECK(randomFd >= 0); PCHECK(randomFd >= 0);
auto bytesRead = readFull(randomFd, data, size); auto bytesRead = readFull(randomFd, data, size);
PCHECK(bytesRead >= 0 && size_t(bytesRead) == size); PCHECK(bytesRead >= 0 && size_t(bytesRead) == size);
#endif
} }
class BufferedRandomDevice { class BufferedRandomDevice {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment