Random Password Generator in Node.JS
The other day I thought about how to generate passwords from random arrays. Here is what I came up with:
/*
* RaNdom Password Generator
*/
const crypto = require('crypto');
const PASSWORD_LENGTH = 18;
const LOWERCASE_ALPHABET = 'abcdefghijklmnopqrstuvwxyz'; // 26 chars
const UPPERCASE_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // 26 chars
const NUMBERS = '0123456789'; // 10 chars
const SYMBOLS = ',./<>?;\'":[]\\|}{=-_+`~!@#$%^&*()'; // 32 chars
const ALPHANUMERIC_CHARS = LOWERCASE_ALPHABET + UPPERCASE_ALPHABET + NUMBERS; // 62 chars
const ALL_CHARS = ALPHANUMERIC_CHARS + SYMBOLS; // 94 chars
function generateRandomPassword(length, alphabet) {
var rb = crypto.randomBytes(length);
var rp = "";
for (var i = 0; i < length; i++) {
rb[i] = rb[i] % alphabet.length;
rp += alphabet[rb[i]];
}
return;
}
console.log("RaNdom Password: " + generateRandomPassword(PASSWORD_LENGTH, LOWERCASE_ALPHABET));
console.log("RaNdom Password: " + generateRandomPassword(PASSWORD_LENGTH, UPPERCASE_ALPHABET));
console.log("RaNdom Password: " + generateRandomPassword(PASSWORD_LENGTH, NUMBERS));
console.log("RaNdom Password: " + generateRandomPassword(PASSWORD_LENGTH, SYMBOLS));
console.log("RaNdom Password: " + generateRandomPassword(PASSWORD_LENGTH, ALPHANUMERIC_CHARS));
console.log("RaNdom Password: " + generateRandomPassword(PASSWORD_LENGTH, ALL_CHARS));
Your output should be similar to this:
pi@raspberrypi:~/Codes/NodeJS/tests $ node npg.js
RaNdom Password: sltfgdvgbnlldhmxjt
RaNdom Password: VJBECQKPFSRMYQCOQU
RaNdom Password: 841107218678249240
RaNdom Password: %#.!)>^~~<""&"?[]_
RaNdom Password: 4eZFsYeRUZmAONPvSG
RaNdom Password: bOPY;90,RBuQ08TvfE