What would be the best approach to creating a 8 character random password containing a-z
, A-Z
and 0-9
?
Absolutely no security issues, this is merely for prototyping, I just want data that looks realistic.
I was thinking a for (0 to 7) Math.random
to produce ASCII codes and convert them to characters. Do you have any other suggestions?
This question is related to
javascript
If you have lodash >= 4.0 in place there is a more elegant way of doing it
var chars = 'abcdefghkmnpqrstuvwxyz23456789';
function generatePassword(length) {
return _.sampleSize(chars, length).join('');
}
Here's a quick dynamic modern solution which I thought I'll share
const generatePassword = (
passwordLength = 8,
useUpperCase = true,
useNumbers = true,
useSpecialChars = true,
) => {
const chars = 'abcdefghijklmnopqrstuvwxyz'
const numberChars = '0123456789'
const specialChars = '!"£$%^&*()'
const usableChars = chars
+ (useUpperCase ? chars.toUpperCase() : '')
+ (useNumbers ? numberChars : '')
+ (useSpecialChars ? specialChars : '')
let generatedPassword = ''
for(i = 0; i <= passwordLength; i++) {
generatedPassword += usableChars[Math.floor(Math.random() * (usableChars.length))]
}
return generatedPassword
}
var createPassword = function() {
var passAt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
var passArray = Array.from({length: 15})
return passArray.map(function(_, index) {
return index % 4 == 3 ? '-' : passAt.charAt(Math.random() * passAt.length)
}).join('')
}
result like:
L5X-La0-bN0-UQO
9eW-svG-OdS-8Xf
ick-u73-2s0-TMX
5ri-PRP-MNO-Z1j
const length = 18; // you can use length as option or static
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const numbers = '0123456789';
const symbols = '!#$%&\()*+,-./:;<=>?@^[\\]^_`{|}~';
let password = '';
let validChars = '';
// all if conditions can be used to custom password
if (useLetters) {
validChars += letters;
}
if (useNumbers) {
validChars += numbers;
}
if (useSymbols) {
validChars += symbols;
}
let generatedPassword = '';
for (let i = 0; i < length; i++) {
const index = Math.floor(Math.random() * validChars.length);
generatedPassword += validChars[index];
}
password = generatedPassword;
This method gives the options to change size and charset of your password.
function generatePassword(length=8, charset="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
return new Array(length)
.fill(null)
.map(()=> charset.charAt(Math.floor(Math.random() * charset.length)))
.join('');
}
console.log(generatePassword()); // 02kdFjzX
console.log(generatePassword(4)); // o8L5
console.log(generatePassword(16)); // jpPd7S09txv9b02p
console.log(generatePassword(16, "abcd1234")); // 4c4d323a31c134dd
This will produce a realistic password if having characters [\]^_
is fine. Requires lodash and es7
String.fromCodePoint(...range(8).map(() => Math.floor(Math.random() * 57) + 0x41))
and here's without lodash
String.fromCodePoint(...Array.from({length: 8}, () => Math.floor(Math.random() * 57) + 65))
function generatePass(pLength){
var keyListAlpha="abcdefghijklmnopqrstuvwxyz",
keyListInt="123456789",
keyListSpec="!@#_",
password='';
var len = Math.ceil(pLength/2);
len = len - 1;
var lenSpec = pLength-2*len;
for (i=0;i<len;i++) {
password+=keyListAlpha.charAt(Math.floor(Math.random()*keyListAlpha.length));
password+=keyListInt.charAt(Math.floor(Math.random()*keyListInt.length));
}
for (i=0;i<lenSpec;i++)
password+=keyListSpec.charAt(Math.floor(Math.random()*keyListSpec.length));
password=password.split('').sort(function(){return 0.5-Math.random()}).join('');
return password;
}
Gumbo's solution does not work. This one does though:
function makePasswd() {
var passwd = '';
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (i=1;i<8;i++) {
var c = Math.floor(Math.random()*chars.length + 1);
passwd += chars.charAt(c)
}
return passwd;
}
This is my function for generating a 8-character crypto-random password:
function generatePassword() {
var buf = new Uint8Array(6);
window.crypto.getRandomValues(buf);
return btoa(String.fromCharCode.apply(null, buf));
}
What it does: Retrieves 6 crypto-random 8-bit integers and encodes them with Base64.
Since the result is in the Base64 character set the generated password may consist of A
-Z
, a
-z
, 0
-9
, +
and /
.
Generate a random password of length 8 to 32 characters with at least 1 lower case, 1 upper case, 1 number, 1 special char (!@$&)
function getRandomUpperCase() {
return String.fromCharCode( Math.floor( Math.random() * 26 ) + 65 );
}
function getRandomLowerCase() {
return String.fromCharCode( Math.floor( Math.random() * 26 ) + 97 );
}
function getRandomNumber() {
return String.fromCharCode( Math.floor( Math.random() * 10 ) + 48 );
}
function getRandomSymbol() {
// const symbol = '!@#$%^&*(){}[]=<>/,.|~?';
const symbol = '!@$&';
return symbol[ Math.floor( Math.random() * symbol.length ) ];
}
const randomFunc = [ getRandomUpperCase, getRandomLowerCase, getRandomNumber, getRandomSymbol ];
function getRandomFunc() {
return randomFunc[Math.floor( Math.random() * Object.keys(randomFunc).length)];
}
function generatePassword() {
let password = '';
const passwordLength = Math.random() * (32 - 8) + 8;
for( let i = 1; i <= passwordLength; i++ ) {
password += getRandomFunc()();
}
//check with regex
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/
if( !password.match(regex) ) {
password = generatePassword();
}
return password;
}
console.log( generatePassword() );
Here's a free, configurable Javascript class generating random passwords: Javascript Random Password Generator.
Examples
Password consisting of Lower case + upper case + numbers, 8 characters long:
var randomPassword = new RandomPassword();
document.write(randomPassword.create());
Password consisting of Lower case + upper case + numbers, 20 characters long:
var randomPassword = new RandomPassword();
document.write(randomPassword.create(20));
Password consisting of Lower case + upper case + numbers + symbols, 20 characters long:
var randomPassword = new RandomPassword();
document.write(randomPassword.create(20,randomPassword.chrLower+randomPassword.chrUpper+randomPassword.chrNumbers+randomPassword.chrSymbols));
Here is a function provides you more options to set min of special chars, min of upper chars, min of lower chars and min of number
function randomPassword(len = 8, minUpper = 0, minLower = 0, minNumber = -1, minSpecial = -1) {
let chars = String.fromCharCode(...Array(127).keys()).slice(33),//chars
A2Z = String.fromCharCode(...Array(91).keys()).slice(65),//A-Z
a2z = String.fromCharCode(...Array(123).keys()).slice(97),//a-z
zero2nine = String.fromCharCode(...Array(58).keys()).slice(48),//0-9
specials = chars.replace(/\w/g, '')
if (minSpecial < 0) chars = zero2nine + A2Z + a2z
if (minNumber < 0) chars = chars.replace(zero2nine, '')
let minRequired = minSpecial + minUpper + minLower + minNumber
let rs = [].concat(
Array.from({length: minSpecial ? minSpecial : 0}, () => specials[Math.floor(Math.random() * specials.length)]),
Array.from({length: minUpper ? minUpper : 0}, () => A2Z[Math.floor(Math.random() * A2Z.length)]),
Array.from({length: minLower ? minLower : 0}, () => a2z[Math.floor(Math.random() * a2z.length)]),
Array.from({length: minNumber ? minNumber : 0}, () => zero2nine[Math.floor(Math.random() * zero2nine.length)]),
Array.from({length: Math.max(len, minRequired) - (minRequired ? minRequired : 0)}, () => chars[Math.floor(Math.random() * chars.length)]),
)
return rs.sort(() => Math.random() > Math.random()).join('')
}
randomPassword(12, 1, 1, -1, -1)// -> DDYxdVcvIyLgeB
randomPassword(12, 1, 1, 1, -1)// -> KYXTbKf9vpMu0
randomPassword(12, 1, 1, 1, 1)// -> hj|9)V5YKb=7
here is a simply smart code :
function generate(l) {
if (typeof l==='undefined'){var l=8;}
/* c : alphanumeric character string */
var c='abcdefghijknopqrstuvwxyzACDEFGHJKLMNPQRSTUVWXYZ12345679',
n=c.length,
/* p : special character string */
p='!@#$+-*&_',
o=p.length,
r='',
n=c.length,
/* s : determinate the position of the special character */
s=Math.floor(Math.random() * (p.length-1));
for(var i=0; i<l; ++i){
if(s == i){
/* special charact insertion (random position s) */
r += p.charAt(Math.floor(Math.random() * o));
}else{
/* alphanumeric insertion */
r += c.charAt(Math.floor(Math.random() * n));
}
}
return r;
}
Simply call generate(), and it do key containing one special character (!@#$+-*&_) for security.
Possible results : WJGUk$Ey, gaV7#fF7, ty_T55DD, YtrQMWveZqYyYKo_
There is more details and example in my website : https://www.bxnxg.com/minituto-01-generer-mots-de-passes-secures-facilements-en-javascript/
Here's another approach based off Stephan Hoyer's solution
getRandomString (length) {
var chars = 'abcdefghkmnpqrstuvwxyz23456789';
return times(length, () => sample(chars)).join('');
}
even shorter:
Array.apply(null, Array(8)).map(function() {
var c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
return c.charAt(Math.random() * c.length);
}).join('');
or as function:
function generatePassword(length, charSet) {
charSet = charSet ? charSet : 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789^°!"§$%&/()=?`*+~\'#,;.:-_';
return Array.apply(null, Array(length || 10)).map(function() {
return charSet.charAt(Math.random() * charSet.length);
}).join('');
}
code to generate a password with password will be given length (default to 8) and have at least one upper case, one lower, one number and one symbol
(2 functions and one const variable called 'allowed')
const allowed = {
uppers: "QWERTYUIOPASDFGHJKLZXCVBNM",
lowers: "qwertyuiopasdfghjklzxcvbnm",
numbers: "1234567890",
symbols: "!@#$%^&*"
}
const getRandomCharFromString = (str) => str.charAt(Math.floor(Math.random() * str.length))
const generatePassword = (length = 8) => { // password will be @Param-length, default to 8, and have at least one upper, one lower, one number and one symbol
let pwd = "";
pwd += getRandomCharFromString(allowed.uppers); //pwd will have at least one upper
pwd += getRandomCharFromString(allowed.lowers); //pwd will have at least one lower
pwd += getRandomCharFromString(allowed.numbers); //pwd will have at least one number
pwd += getRandomCharFromString(allowed.symbols);//pwd will have at least one symbolo
for (let i = pwd.length; i < length; i++)
pwd += getRandomCharFromString(Object.values(allowed).join('')); //fill the rest of the pwd with random characters
return pwd
}
Here is a solution I found, if you look at the source of the page you can see how they implement their examples as well:
https://www.404it.no/en/blog/javascript_random_password_generator
Javascript Random Password Generator Published: January 6th 2015 Updated: January 18th 2015 Author: Per Kristian Haakonsen
My pain point is that every Sign-Up tool allows a different set of special characters. Some might only allow these @#$%&*
while others maybe don't allow *
but do allow other things. Every password generator I've come across is binary when it comes to special characters. It allows you to either include them or not. So I wind up cycling through tons of options and scanning for outliers that don't meet the requirements until I find a password that works. The longer the password the more tedious this becomes. Finally, I have noticed that sometimes Sign-Up tools don't let you repeat the same character twice in a row but password generators don't seem to account for this. It's madness!
I made this for myself so I can just paste in the exact set of special characters that are allowed. I do not pretend this is elegant code. I just threw it together to meet my needs.
Also, I couldn't think of a time when a Sign-Up tool did not allow numbers or wasn't case sensitive so my passwords always have at least one number, one upper case letter, one lower case letter, and one special character. This means the minimum length is 4. Technically I can get around the special character requirement by just entering a letter if need be.
const getPassword = (length, arg) => {_x000D_
length = document.getElementById("lengthInput").value || 16;_x000D_
arg = document.getElementById("specialInput").value || "~!@#$%^&*()_+-=[]{}|;:.,?><";_x000D_
if (length < 4) {_x000D_
updateView("passwordValue", "passwordValue", "", "P", "Length must be at least 4");_x000D_
return console.error("Length must be at least 4")_x000D_
} else if (length > 99) {_x000D_
updateView("passwordValue", "passwordValue", "", "P", "Length must be less then 100");_x000D_
return console.error("Length must be less then 100")_x000D_
}_x000D_
const lowercase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];_x000D_
const uppercase = lowercase.join("").toUpperCase().split("");_x000D_
const specialChars = arg.split("").filter(item => item.trim().length);_x000D_
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]_x000D_
let hasNumber = false;_x000D_
let hasUpper = false;_x000D_
let hasLower = false;_x000D_
let hasSpecial = false;_x000D_
_x000D_
if (Number(length)) {_x000D_
length = Number(length)_x000D_
} else {_x000D_
return console.error("Enter a valid length for the first argument.")_x000D_
}_x000D_
_x000D_
let password = [];_x000D_
let lastChar;_x000D_
for (let i = 0; i < length; i++) {_x000D_
let char = newChar(lowercase, uppercase, numbers, specialChars);_x000D_
if (char !== lastChar) {_x000D_
password.push(char);_x000D_
lastChar = char_x000D_
if (Number(char)) {_x000D_
hasNumber = true_x000D_
}_x000D_
if (lowercase.indexOf(char) > -1) {_x000D_
hasLower = true_x000D_
}_x000D_
if (uppercase.indexOf(char) > -1) {_x000D_
hasUpper = true_x000D_
}_x000D_
if (specialChars.indexOf(char) > -1) {_x000D_
hasSpecial = true_x000D_
}_x000D_
} else {_x000D_
i--_x000D_
}_x000D_
if (i === length - 1 && (!hasNumber || !hasUpper || !hasLower || !hasSpecial)) {_x000D_
hasNumber = false;_x000D_
hasUpper = false;_x000D_
hasLower = false;_x000D_
hasSpecial = false;_x000D_
password = [];_x000D_
i = -1;_x000D_
}_x000D_
}_x000D_
_x000D_
function newChar(lower, upper, nums, specials) {_x000D_
let set = [lower, upper, nums, specials];_x000D_
let pick = set[Math.floor(Math.random() * set.length)];_x000D_
return pick[Math.floor(Math.random() * pick.length)]_x000D_
}_x000D_
updateView("passwordValue", "passwordValue", "", "P", password.join(""));_x000D_
updateView("copyPassword", "copyPassword", "", "button", "copy text");_x000D_
document.getElementById("copyPassword").addEventListener("click", copyPassword);_x000D_
}_x000D_
_x000D_
const copyPassword = () => {_x000D_
let text = document.getElementById("passwordValue").textContent;_x000D_
navigator.clipboard.writeText(text);_x000D_
};_x000D_
_x000D_
const updateView = (targetId, newId, label, element, method = '') => {_x000D_
let newElement = document.createElement(element);_x000D_
newElement.id = newId;_x000D_
let content = document.createTextNode(label + method);_x000D_
newElement.appendChild(content);_x000D_
_x000D_
let currentElement = document.getElementById(targetId);_x000D_
let parentElement = currentElement.parentNode;_x000D_
parentElement.replaceChild(newElement, currentElement);_x000D_
}_x000D_
_x000D_
document.getElementById("getPassword").addEventListener("click", getPassword);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div>_x000D_
<button id="getPassword">Generate Password</button>_x000D_
<input type="number" id="lengthInput" placeholder="Length">_x000D_
<input type="text" id="specialInput" placeholder="Special Characters">_x000D_
<p id="passwordValue"></p>_x000D_
<p id="copyPassword"></p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I got insprired by the answers above (especially by the hint from @e.vyushin regarding the security of Math.random() ) and I came up with the following solution that uses the crypto.getRandomValues() to generate a rondom array of UInt32 values with the length of the password length.
Then, it loops through the array and devides each element by 2^32 (max value of a UInt32) to calculate the ratio between the actual value and the max. possible value. This ratio is then mapped to the charset string to determine which character of the string is picked.
console.log(createPassword(16,"letters+numbers+signs"));
function createPassword(len, charset) {
if (charset==="letters+numbers") {
var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
} else if (charset==="letters+numbers+signs") {
var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!§$%&/?#+-_@";
}
var arr = new Uint32Array(len);
var maxRange = Math.pow(2,32);
var passwd = '';
window.crypto.getRandomValues(arr);
for (let i=0;i<len;i++) {
var c = Math.floor(arr[i] / maxRange * chars.length + 1);
passwd += chars.charAt(c);
}
return passwd;
}
Thus, the code is able to use the advantage of the crypto-Class (improved security for the random value generation) and is adaptable to use any kind of charset the user wished. A next step would be to use regular expression strings to define the charset to be used.
function genPass(n) // e.g. pass(10) return 'unQ0S2j9FY'
{
let c='abcdefghijklmnopqrstuvwxyz'; c+=c.toUpperCase()+1234567890;
return [...Array(n)].map(b=>c[~~(Math.random()*62)]).join('')
}
Where n
is number of output password characters; 62
is c.length
and where e.g. ~~4.5 = 4
is trick for replace Math.floor
function genPass(n) // e.g. pass(10) return 'unQ0S2j9FY'
{
let c='abcdefghijklmnopqrstuvwxyz'; c+=c.toUpperCase()+1234567890;
return '-'.repeat(n).replace(/./g,b=>c[~~(Math.random()*62)])
}
to extend characters list, add them to c
e.g. to add 10 characters !$^&*-=+_?
write c+=c.toUpperCase()+1234567890+'!$^&*-=+_?'
and change Math.random()*62
to Math.random()*72
(add 10 to 62).
function genPass(){
//https://sita.app/password-generator
let stringInclude = '';
stringInclude += "!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~";
stringInclude += '0123456789';
stringInclude += 'abcdefghijklmnopqrstuvwxyz';
stringInclude += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var password ='';
for (let i = 0; i < 40; i++) {
password += stringInclude.charAt(Math.floor(Math.random() * stringInclude.length));
}
return password;
}
Randomly assigns Alpha, Numeric, Caps and Special per character then validates the password. If it doesn't contain each of the above, randomly assigns a new character from the missing element to a random existing character then recursively validates until a password is formed:
function createPassword(length) {
var alpha = "abcdefghijklmnopqrstuvwxyz";
var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numeric = "0123456789";
var special = "!$^&*-=+_?";
var options = [alpha, caps, numeric, special];
var password = "";
var passwordArray = Array(length);
for (i = 0; i < length; i++) {
var currentOption = options[Math.floor(Math.random() * options.length)];
var randomChar = currentOption.charAt(Math.floor(Math.random() * currentOption.length));
password += randomChar;
passwordArray.push(randomChar);
}
checkPassword();
function checkPassword() {
var missingValueArray = [];
var containsAll = true;
options.forEach(function (e, i, a) {
var hasValue = false;
passwordArray.forEach(function (e1, i1, a1) {
if (e.indexOf(e1) > -1) {
hasValue = true;
}
});
if (!hasValue) {
missingValueArray = a;
containsAll = false;
}
});
if (!containsAll) {
passwordArray[Math.floor(Math.random() * passwordArray.length)] = missingValueArray.charAt(Math.floor(Math.random() * missingValueArray.length));
password = "";
passwordArray.forEach(function (e, i, a) {
password += e;
});
checkPassword();
}
}
return password;
}
This is the quickest and easiest way I know of:
Math.random().toString(36).slice(2)
The idea is to cast a random number (in the range 0..1) to a base36 string (lowercase a-z plus 0-9) and remove the leading zero and decimal point.
Please note that all passwords that is pseudo-generated have some form of vulnerability. However, I would say it is good enough for all normal use-cases. Furthermore, the theoretical length if this password is not guaranteed. It is 16 characters maximum and 0 characters minimum. When run in a loop 1 million times its average length is 15.67 characters with a minimum length of 5. However if you join two of these passwords together, you will get a maximum length of 32 characters, with an average length of 31.33 chars and a minimum length of 20.
Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2)
Personally I use this as a chrome bookmarklet
in my browser bookmarks bar to speedily generate passwords:
javascript:(
function(){
prompt('Here is your shiny new password:',
Math.random().toString(36).slice(2) +
Math.random().toString(36).slice(2)
);
}
)();
function password_generator( len ) {
var length = (len)?(len):(10);
var string = "abcdefghijklmnopqrstuvwxyz"; //to upper
var numeric = '0123456789';
var punctuation = '!@#$%^&*()_+~`|}{[]\:;?><,./-=';
var password = "";
var character = "";
var crunch = true;
while( password.length<length ) {
entity1 = Math.ceil(string.length * Math.random()*Math.random());
entity2 = Math.ceil(numeric.length * Math.random()*Math.random());
entity3 = Math.ceil(punctuation.length * Math.random()*Math.random());
hold = string.charAt( entity1 );
hold = (password.length%2==0)?(hold.toUpperCase()):(hold);
character += hold;
character += numeric.charAt( entity2 );
character += punctuation.charAt( entity3 );
password = character;
}
password=password.split('').sort(function(){return 0.5-Math.random()}).join('');
return password.substr(0,len);
}
console.log( password_generator() );
This generates a little more robust password that should pass any password strength test. eg: f1&d2?I4(h1&
, C1^y1)j1@G2#
, j2{h6%b5@R2)
I see much examples on this page are using Math.random. This method hasn't cryptographically strong random values so it's unsecure. Instead Math.random recomended use getRandomValues or your own alhorytm.
You can use passfather. This is a package that are using much cryptographically strong alhorytmes. I'm owner of this package so you can ask some question.
I also developed my own password generator, with random length (between 16 and 40 by default), strong passwords, maybe it could help.
function randomChar(string) {
return string[Math.floor(Math.random() * string.length)];
}
// you should use another random function, like the lodash's one.
function random(min = 0, max = 1) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// you could use any shuffle function, the lodash's one, or the following https://stackoverflow.com/a/6274381/6708504
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function generatePassword() {
const symbols = '§±!@#$%^&*()-_=+[]{}\\|?/<>~';
const numbers = '0123456789';
const lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
const uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const minCharsGroup = 4;
const maxCharsGroup = 10;
const randomSymbols = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(symbols));
const randomNumbers = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(numbers));
const randomUppercasesLetters = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(uppercaseLetters));
const randomLowercasesLetters = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(lowercaseLetters));
const chars = [...randomSymbols, ...randomNumbers, ...randomUppercasesLetters, ...randomLowercasesLetters];
return shuffle(chars).join('');
}
A simple lodash solution that warranties 14 alpha, 3 numeric and 3 special characters, not repeated:
const generateStrongPassword = (alpha = 14, numbers = 3, special = 3) => {
const alphaChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numberChars = '0123456789';
const specialChars = '!"£$%^&*()-=+_?';
const pickedChars = _.sampleSize(alphaChars, alpha)
.concat(_.sampleSize(numberChars, numbers))
.concat(_.sampleSize(specialChars, special));
return _.shuffle(pickedChars).join('');
}
const myPassword = generateStrongPassword();
Source: Stackoverflow.com