mirror of https://github.com/aria2/aria2
Make generateRandomBytes less biased.
parent
213de910fd
commit
86c61fcf5b
|
@ -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
|
||||
|
|
|
@ -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);
|
||||
};
|
||||
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
Loading…
Reference in New Issue