Skip to content

Instantly share code, notes, and snippets.

@devm33
Last active March 3, 2022 09:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save devm33/9443419 to your computer and use it in GitHub Desktop.
Save devm33/9443419 to your computer and use it in GitHub Desktop.
Generate Random Hex String in NodeJS
function rand_string(n) {
if (n <= 0) {
return '';
}
var rs = '';
try {
rs = crypto.randomBytes(Math.ceil(n/2)).toString('hex').slice(0,n);
/* note: could do this non-blocking, but still might fail */
}
catch(ex) {
/* known exception cause: depletion of entropy info for randomBytes */
console.error('Exception generating random string: ' + ex);
/* weaker random fallback */
rs = '';
var r = n % 8, q = (n-r)/8, i;
for(i = 0; i < q; i++) {
rs += Math.random().toString(16).slice(2);
}
if(r > 0){
rs += Math.random().toString(16).slice(2,i);
}
}
return rs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment