Created
August 27, 2011 07:38
-
-
Save Marak/1175107 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
// | |
// ### 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