mirror of
https://github.com/keepassxreboot/keepassxc.git
synced 2024-12-28 08:49:42 -05:00
Avoid modulo bias in Random::randomUInt().
This commit is contained in:
parent
b64276c4e8
commit
e087baeb48
@ -21,6 +21,10 @@
|
||||
|
||||
#include "crypto/Crypto.h"
|
||||
|
||||
#ifndef QUINT32_MAX
|
||||
#define QUINT32_MAX 4294967295U
|
||||
#endif
|
||||
|
||||
void Random::randomize(QByteArray& ba)
|
||||
{
|
||||
randomize(ba.data(), ba.size());
|
||||
@ -38,8 +42,18 @@ QByteArray Random::randomArray(int len)
|
||||
|
||||
quint32 Random::randomUInt(quint32 limit)
|
||||
{
|
||||
Q_ASSERT(limit != 0);
|
||||
Q_ASSERT(limit <= QUINT32_MAX);
|
||||
|
||||
quint32 rand;
|
||||
const quint32 ceil = QUINT32_MAX - (QUINT32_MAX % limit) - 1;
|
||||
|
||||
// To avoid modulo bias:
|
||||
// Make sure rand is below the largest number where rand%limit==0
|
||||
do {
|
||||
randomize(&rand, 4);
|
||||
} while (rand > ceil);
|
||||
|
||||
return (rand % limit);
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user