Fixed random bias.

Ylian Saint-Hilaire committed Feb 8, 2021 at 18:23 UTC 956fdd8ca891de7f1607a8ae7b8eefc652871c41
2 files changed +10 -3
common.js
+8 -2
@@ -95,8 +95,14 @@ module.exports.data2blob = function (data) {
95 return blob;
96 };
97
98 -// Generate random numbers
99 -module.exports.random = function (max) { (require('crypto').randomBytes(4).readUInt32BE(0) % max); };
98 +// Generate random numbers between 0 and max without bias.
99 +module.exports.random = function (max) {
100 + const crypto = require('crypto');
101 + var maxmask = 1, r;
102 + while (maxmask < max) { maxmask = (maxmask << 1) + 1; }
103 + do { r = (crypto.randomBytes(4).readUInt32BE(0) & maxmask); } while (r > max);
104 + return r;
105 +};
106
107 // Split a comma seperated string, ignoring commas in quotes.
108 module.exports.quoteSplit = function (str) {
multiserver.js
+2 -1
@@ -178,7 +178,8 @@ module.exports.CreateMultiServer = function (parent, args) {
178
179 // Get the next retry time in milliseconds
180 function getConnectRetryTime() {
181 - if (obj.retryBackoff < 30000) { obj.retryBackoff += ((require('crypto').randomBytes(4).readUInt32BE(0) % 3000) + 1000); }
181 + // The (random & 0x1FFF) creates a random number between 0 and 4096.
182 + if (obj.retryBackoff < 30000) { obj.retryBackoff += ((require('crypto').randomBytes(4).readUInt32BE(0) & 0x1FFF) + 1000); }
183 return obj.retryBackoff;
184 }
185