Chromium Code Reviews| Index: base/rand_util_win.cc |
| diff --git a/base/rand_util_win.cc b/base/rand_util_win.cc |
| index 35f2d2e863ab83f84e0c00dffe19872f808fa43a..3047a7ac904c887798f17a5bfd2ca557482c59c5 100644 |
| --- a/base/rand_util_win.cc |
| +++ b/base/rand_util_win.cc |
| @@ -4,18 +4,34 @@ |
| #include "base/rand_util.h" |
| +#include <limits.h> |
|
wtc
2014/01/22 22:42:04
I don't think you are using anything from the C he
|
| +#include <stdint.h> |
| #include <stdlib.h> |
| +#include <windows.h> |
| -#include "base/basictypes.h" |
| +#include "base/lazy_instance.h" |
| #include "base/logging.h" |
| namespace { |
|
wtc
2014/01/22 22:42:04
Nit: add a blank line after this line.
|
| +typedef BOOLEAN (WINAPI *RtlGenRandomPtr)(PVOID, ULONG); |
| + |
| +class WinRandom { |
| + public: |
| + WinRandom() |
| + : rtl_gen_random_(reinterpret_cast<RtlGenRandomPtr>( |
| + ::GetProcAddress(::GetModuleHandle(L"advapi32.dll"), |
| + "SystemFunction036"))) {} |
| + ~WinRandom() {} |
| + |
| + void RtlGenRandom(void* output, uint32_t output_length) const { |
| + CHECK_EQ(rtl_gen_random_(output, output_length), TRUE); |
| + } |
| -uint32 RandUint32() { |
| - uint32 number; |
| - CHECK_EQ(rand_s(&number), 0); |
| - return number; |
| -} |
| + private: |
| + const RtlGenRandomPtr rtl_gen_random_; |
| +}; |
| + |
| +base::LazyInstance<WinRandom>::Leaky g_win_random = LAZY_INSTANCE_INITIALIZER; |
| } // namespace |
| @@ -23,18 +39,20 @@ namespace base { |
| // NOTE: This function must be cryptographically secure. http://crbug.com/140076 |
| uint64 RandUint64() { |
| - uint32 first_half = RandUint32(); |
| - uint32 second_half = RandUint32(); |
| - return (static_cast<uint64>(first_half) << 32) + second_half; |
| + uint64 number; |
| + g_win_random.Pointer()->RtlGenRandom(&number, sizeof(number)); |
| + return number; |
| } |
| void RandBytes(void* output, size_t output_length) { |
| - uint64 random_int; |
| - const size_t random_int_size = sizeof(random_int); |
| - for (size_t i = 0; i < output_length; i += random_int_size) { |
| - random_int = base::RandUint64(); |
| - size_t copy_count = std::min(output_length - i, random_int_size); |
| - memcpy(((uint8*)output) + i, &random_int, copy_count); |
| + char* output_ptr = static_cast<char*>(output); |
| + const WinRandom* win_random_ptr = g_win_random.Pointer(); |
|
wtc
2014/01/22 22:42:04
Nit: this should be
const WinRandom* const win_r
|
| + while (output_length > 0) { |
| + const uint32_t output_bytes_this_pass = static_cast<uint32_t>( |
| + std::min(output_length, std::numeric_limits<uint32_t>::max())); |
| + win_random_ptr->RtlGenRandom(output_ptr, output_bytes_this_pass); |
| + output_length -= output_bytes_this_pass; |
| + output_ptr += output_bytes_this_pass; |
| } |
| } |