fixes bug in randBits()

- the bug was causing the whole first byte to be zeroed out when (bitLength % 8 === 0)
 - added a check of the above condition before zeroing out the extra bits
This commit is contained in:
Coffee Converter 2020-03-24 15:39:16 -05:00
parent 7bc770bb8c
commit 36d9786b3d
1 changed files with 4 additions and 2 deletions

View File

@ -401,8 +401,10 @@ export function randBits(bitLength, forceLength = false) {
const byteLength = Math.ceil(bitLength / 8); const byteLength = Math.ceil(bitLength / 8);
let rndBytes = randBytesSync(byteLength, false); let rndBytes = randBytesSync(byteLength, false);
// Fill with 0's the extra bits if (bitLength % 8) {
rndBytes[0] = rndBytes[0] & (2 ** (bitLength % 8) - 1); // Fill with 0's the extra bits
rndBytes[0] = rndBytes[0] & (2 ** (bitLength % 8) - 1);
}
if (forceLength) { if (forceLength) {
let mask = (bitLength % 8) ? 2 ** ((bitLength % 8) - 1) : 128; let mask = (bitLength % 8) ? 2 ** ((bitLength % 8) - 1) : 128;
rndBytes[0] = rndBytes[0] | mask; rndBytes[0] = rndBytes[0] | mask;