Skip to content

Commit

Permalink
Fix less than ideal random digits generator. Closes #34
Browse files Browse the repository at this point in the history
  • Loading branch information
hueniverse committed Jun 24, 2018
1 parent 96e63fd commit 9332d42
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
33 changes: 25 additions & 8 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,21 @@ exports.randomString = function (size) {

exports.randomDigits = function (size) {

const buffer = exports.randomBits(size * 8);
const digits = [];
for (let i = 0; i < buffer.length; ++i) {
digits.push(Math.floor(buffer[i] / 25.6));

let buffer = internals.random(size * 2); // Provision twice the amount of bytes needed to increase chance of single pass
let pos = 0;

while (digits.length < size) {
if (pos >= buffer.length) {
buffer = internals.random(size * 2);
pos = 0;
}

if (buffer[pos] < 250) {
digits.push(buffer[pos] % 10);
}
++pos;
}

return digits.join('');
Expand All @@ -47,21 +58,27 @@ exports.randomBits = function (bits) {
}

const bytes = Math.ceil(bits / 8);
return internals.random(bytes);
};


exports.fixedTimeComparison = function (a, b) {

try {
return Crypto.randomBytes(bytes);
return Crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
}
catch (err) {
throw Boom.internal('Failed generating random bits: ' + err.message);
return false;
}
};


exports.fixedTimeComparison = function (a, b) {
internals.random = function (bytes) {

try {
return Crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
return Crypto.randomBytes(bytes);
}
catch (err) {
return false;
throw Boom.internal('Failed generating random bits: ' + err.message);
}
};
12 changes: 12 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ describe('randomDigits()', () => {

expect(() => Cryptiles.randomDigits(99999999999999999999)).to.throw(/Failed generating random bits/);
});

it('generates equal digits distribution', () => {

const digits = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0 };
for (let i = 0; i < 1000000; ++i) {
digits[Cryptiles.randomDigits(1)] += 1;
}

for (const digit in digits) {
expect(digits[digit]).to.be.between(99000, 101000);
}
});
});

describe('randomBits()', () => {
Expand Down

0 comments on commit 9332d42

Please sign in to comment.