From ac9608ca8dcbc333a606b423ff098b0fb5db21a2 Mon Sep 17 00:00:00 2001 From: svanstone-resilient <62011179+svanstone-resilient@users.noreply.github.com> Date: Mon, 7 Feb 2022 10:59:12 +0000 Subject: [PATCH] Allow random to return full range Previously only returned from 0 to 0.5. This removed 2 bits of entropy from the generated cuids. This is a replacement for Math.random() and as such it should return from 0 to 1 (but never return 1 exactly), therefore lim was also modified. The returned value now has about 30 to 32 bits of entropy. This is probably enough for this library (it gets truncated to 20 bits later), but you could consider using something like this library: https://github.com/emilbayes/secure-random-double/blob/master/index.js Which would allow you to get 51 or 52 bits of entropy into the return value. --- lib/getRandomValue.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/getRandomValue.js b/lib/getRandomValue.js index 5d8797d..e2c24d2 100644 --- a/lib/getRandomValue.js +++ b/lib/getRandomValue.js @@ -1,9 +1,8 @@ var crypto = require('crypto'); -var lim = Math.pow(2, 32) - 1; +var lim = Math.pow(2, 32); module.exports = function random () { - return Math.abs(crypto.randomBytes(4) - .readInt32BE() / lim); + return crypto.randomBytes(4).readUInt32BE() / lim; };