Created
August 9, 2017 11:04
-
-
Save uniibu/def853f402ded65b5c3111c7d489ea73 to your computer and use it in GitHub Desktop.
Generate random alphanumeric string using nodejs crypto module
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
const crypto = require('crypto'); | |
const alphanumeric = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; | |
function randomize(seed, len) { | |
const sourceArray = seed.split(''); | |
let baselen = typeof len === 'undefined' ? sourceArray.length : len; | |
const rnd = crypto.randomBytes(baselen); | |
const result = []; | |
let counter = 0, characterIndex, r; | |
while (baselen > 0) { | |
r = rnd[counter]; | |
characterIndex = r % sourceArray.length; | |
result.push(sourceArray.splice(characterIndex, 1)[0]); | |
baselen--; | |
counter++; | |
} | |
return result.join(''); | |
} | |
function generate(len,prepend='') { | |
const alphaseed = randomize(alphanumeric); | |
return randomize(alphaseed, len) + prepend | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@uniibu Since I have no clue about cryptography: sicne 6 years have passed, would you consider this as a strong random generator?