Skip to content

Instantly share code, notes, and snippets.

@uniibu
Created August 9, 2017 11:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uniibu/def853f402ded65b5c3111c7d489ea73 to your computer and use it in GitHub Desktop.
Save uniibu/def853f402ded65b5c3111c7d489ea73 to your computer and use it in GitHub Desktop.
Generate random alphanumeric string using nodejs crypto module
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
}
@eko2one
Copy link

eko2one commented Mar 20, 2023

@uniibu Since I have no clue about cryptography: sicne 6 years have passed, would you consider this as a strong random generator?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment