Skip to content

Instantly share code, notes, and snippets.

@medikoo
Forked from Marak/gist:1175107
Created August 27, 2011 09:10
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 medikoo/1175177 to your computer and use it in GitHub Desktop.
Save medikoo/1175177 to your computer and use it in GitHub Desktop.
//
// ### function randomString (bits)
// #### @bits {integer} The number of bits for the random base64 string returned to contain
// randomString returns a pseude-random ASCII string which contains at least the specified number of bits of entropy
// the return value is a string of length ⌈bits/6⌉ of characters from the base64 alphabet
//
helpers.randomString = exports.randomString = function (bits) {
var chars, rand, i, ret;
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
ret = '';
// in v8, Math.random() yields 32 pseudo-random bits (in spidermonkey it gives 53)
while (bits > 0) {
// 32-bit integer
rand = Math.floor(Math.random() * 0x100000000);
// base 64 means 6 bits per character, so we use the top 30 bits from rand to give 30/6=5 characters.
for (i = 26; i > 0 && bits > 0; i -= 6, bits -= 6) {
ret += chars[0x3F & rand >>> i];
}
}
return ret;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment