From 86c61fcf5b56ede1f30d38ae856634b7913b80e7 Mon Sep 17 00:00:00 2001 From: Nils Maier Date: Mon, 23 Sep 2013 15:51:25 +0200 Subject: [PATCH] Make generateRandomBytes less biased. --- src/SimpleRandomizer.cc | 19 +++++++++++++++++++ src/SimpleRandomizer.h | 2 ++ src/util.cc | 4 +--- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/SimpleRandomizer.cc b/src/SimpleRandomizer.cc index aaba91a4..fea7262f 100644 --- a/src/SimpleRandomizer.cc +++ b/src/SimpleRandomizer.cc @@ -115,4 +115,23 @@ long int SimpleRandomizer::operator()(long int to) return getRandomNumber(to); } +void SimpleRandomizer::getRandomBytes(unsigned char *buf, size_t len) +{ +#ifdef __MINGW32__ + if (!CryptGenRandom(cryProvider_, len, (PBYTE)buf)) { + throw std::bad_alloc(); + } +#else + while (len) { + union { + int32_t r; + uint8_t b[4]; + } r = { (int32_t)random() }; + for (auto i = 0; i < 4 && len; ++i, --len) { + *buf++ = r.b[i]; + } + } +#endif +} + } // namespace aria2 diff --git a/src/SimpleRandomizer.h b/src/SimpleRandomizer.h index ffcb33ec..7e0afad9 100644 --- a/src/SimpleRandomizer.h +++ b/src/SimpleRandomizer.h @@ -71,6 +71,8 @@ public: */ virtual long int getRandomNumber(long int to) CXX11_OVERRIDE; + void getRandomBytes(unsigned char *buf, size_t len); + long int operator()(long int to); }; diff --git a/src/util.cc b/src/util.cc index e075dfd0..06d41a41 100644 --- a/src/util.cc +++ b/src/util.cc @@ -1595,9 +1595,7 @@ namespace { void generateRandomDataRandom(unsigned char* data, size_t length) { const auto& rd = SimpleRandomizer::getInstance(); - for(size_t i = 0; i < length; ++i) { - data[i] = static_cast(rd->getRandomNumber(256)); - } + rd->getRandomBytes(data, length); } } // namespace