Make generateRandomBytes less biased.

pull/130/head
Nils Maier 2013-09-23 15:51:25 +02:00
parent 213de910fd
commit 86c61fcf5b
3 changed files with 22 additions and 3 deletions

View File

@ -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

View File

@ -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);
};

View File

@ -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<unsigned long>(rd->getRandomNumber(256));
}
rd->getRandomBytes(data, length);
}
} // namespace