Created
January 15, 2018 00:58
-
-
Save dstaley/35e9310b914b1291063a3f330c921553 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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