From: Orvid King Date: Mon, 17 Aug 2015 17:32:51 +0000 (-0700) Subject: Implement Random.cpp for MSVC X-Git-Tag: v0.54.0~3 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=9af380441971bc1d285c1c64cea3e3d80fe45079;p=folly.git Implement Random.cpp for MSVC Summary: This uses `` to implement it, because there is no `/dev/urandom` on Windows. Closes #250 Reviewed By: @yfeldblum Differential Revision: D2282887 Pulled By: @sgolemon --- diff --git a/folly/Random.cpp b/folly/Random.cpp index 87da68b6..62eb8f9f 100644 --- a/folly/Random.cpp +++ b/folly/Random.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -26,16 +27,31 @@ #include #include +#ifdef _MSC_VER +# include +#endif + namespace folly { namespace { 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::max()); + PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data)); +#else // Keep the random device open for the duration of the program. static int randomFd = ::open("/dev/urandom", O_RDONLY); PCHECK(randomFd >= 0); auto bytesRead = readFull(randomFd, data, size); PCHECK(bytesRead >= 0 && size_t(bytesRead) == size); +#endif } class BufferedRandomDevice {