Skip to content

Instantly share code, notes, and snippets.

@dstaley
Created January 15, 2018 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dstaley/35e9310b914b1291063a3f330c921553 to your computer and use it in GitHub Desktop.
Save dstaley/35e9310b914b1291063a3f330c921553 to your computer and use it in GitHub Desktop.
// Adapted from Python's implementation of randrange.
// https://github.com/python/cpython/blob/master/Lib/random.py
const crypto = require('crypto');
const bases = require('bases');
const START = 33554432; // '100000'
const END = 1073741824; // 'ZZZZZZ'
function getrandbits(k) {
const numbytes = Math.floor((k + 7) / 8);
const x = crypto.randomBytes(numbytes).readUIntBE(0, numbytes);
return x >>> (numbytes * 8 - k);
}
function randbelow(n) {
const k = n.toString(2).length;
let r = getrandbits(k);
while (r >= n) {
r = getrandbits(k);
}
return r;
}
function randrange(start, stop) {
const width = stop - start;
return start + randbelow(width);
}
function getRandomKey() {
return bases.toBase32(randrange(START, END));
}
module.exports = getRandomKey;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment