Last active
March 3, 2022 09:00
-
-
Save devm33/9443419 to your computer and use it in GitHub Desktop.
Generate Random Hex String in NodeJS
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 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