mirror of
https://github.com/keepassxreboot/keepassxc.git
synced 2025-07-31 10:39:14 -04:00
Avoid modulo bias in Random::randomUInt().
This commit is contained in:
parent
b64276c4e8
commit
e087baeb48
1 changed files with 15 additions and 1 deletions
|
@ -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…
Add table
Add a link
Reference in a new issue