From 20b489a6cfd69275c896136a3f7aac2726faebd6 Mon Sep 17 00:00:00 2001 From: tomsmeding Date: Thu, 16 Jan 2020 17:16:54 +0100 Subject: server: Uniformly random id generator --- server/serverstore.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'server') diff --git a/server/serverstore.js b/server/serverstore.js index e10ae9a..745877f 100755 --- a/server/serverstore.js +++ b/server/serverstore.js @@ -30,9 +30,22 @@ renewChallenge(); function gencode(){ var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + + var domainsize = Math.pow(256, 5); + var targetsize = Math.pow(62, 6); + var limit = domainsize - (domainsize % targetsize); + + var number; + do { + var bytes = crypto.randomBytes(5); // 62^6 < 256^5, so large enough + number = 0; // 256^5 < 2^52, so fits in JS's double + for (var i = 0; i < 5; i++) number = 256 * number + bytes[i]; + } while (number >= limit); // ensure uniformity + var code = ""; for(var i = 0; i < 6; i++) { - code += alphabet[~~(Math.random() * alphabet.length)]; + code += alphabet[number % 62]; + number = Math.floor(number / 62); } return code; } -- cgit v1.2.3-70-g09d2