Loopless getRandomBN using extra random bits
This commit is contained in:
parent
d529edfdda
commit
a79acf0386
|
@ -107,22 +107,14 @@ export default {
|
||||||
throw new Error('Illegal parameter value: max <= min');
|
throw new Error('Illegal parameter value: max <= min');
|
||||||
}
|
}
|
||||||
|
|
||||||
let r;
|
const modulus = max.sub(min);
|
||||||
const diff = max.sub(min);
|
const bytes = modulus.byteLength();
|
||||||
const bits = diff.bitLength();
|
|
||||||
const bytes = diff.byteLength();
|
|
||||||
|
|
||||||
// Using a while loop is necessary to avoid bias
|
// Using a while loop is necessary to avoid bias introduced by the mod operation.
|
||||||
// TODO consider using 64 extra random bits and taking mod
|
// However, we request 64 extra random bits so that the bias is negligible.
|
||||||
// Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
// Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
||||||
do {
|
const r = new BN(this.getRandomBytes(bytes + 8));
|
||||||
r = new BN(this.getRandomBytes(bytes));
|
return r.mod(modulus).add(min);
|
||||||
if (r.bitLength() > bits) {
|
|
||||||
r.ishrn(r.bitLength() - bits);
|
|
||||||
}
|
|
||||||
} while (r.cmp(diff) >= 0);
|
|
||||||
|
|
||||||
return r.iadd(min);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
randomBuffer: new RandomBuffer()
|
randomBuffer: new RandomBuffer()
|
||||||
|
|
Loading…
Reference in New Issue
Block a user