我创建了一个简单的密码生成器,它也可以进行强度检查。但是,如果它无法生成足够强的密码,我将很难决定如何处理。此时,它仅显示创建失败消息。
如果创建的密码强度不够,我应该定义密码创建规则还是只是重新启动该功能?任何意见,建议或线索,不胜感激。谢谢。
代码可以在下面找到。
'use strict';
let generatePassword = function(passwordLength = 10) {
let alphabetString = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890-_=+[]{}!@#$%^&*();:'|\,<.>/?`",
alphabet = alphabetString.split("",),
passwordArray = [],
getRandomSymbol = function() {
return alphabet[Math.floor(Math.random()*alphabet.length)]
};
for (let i = 0; i < passwordLength; i++) {
passwordArray.push(getRandomSymbol());
}
let password = passwordArray.join(""),
passwordStrengthCheck = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
if (password.match(passwordStrengthCheck)) {
return console.log(`Your password is: ${password}`);
} else {
console.log("Failed to generate a strong enough password");
}
}
// Function call sample:
generatePassword();
答案 0 :(得分:0)
要确保您的密码在所有组中至少包含一个符号,请执行以下操作:
all
拾取休息字符代码:
let generatePassword = function(passwordLength = 10) {
let capitals = "QWERTYUIOPASDFGHJKLZXCVBNM";
let small = "qwertyuiopasdfghjklzxcvbnm";
let digits = "1234567890";
let symbols = "-_=+[]{}!@#$%^&*();:'|\,<.>/?`",
let all = capitals + small + digits + symbols;
getRandomSymbol = function(sourceString) {
return sourceString[Math.floor(Math.random()*sourceString.length)]
};
alphabet = alphabetString.split("",),
passwordArray = [],
passwordArray.push(getRandomSymbol(capitals));
passwordArray.push(getRandomSymbol(small));
passwordArray.push(getRandomSymbol(digits));
passwordArray.push(getRandomSymbol(symbols));
for (let i = 0; i < passwordLength - 4; i++) {
passwordArray.push(getRandomSymbol(all));
}
shuffle = function (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;
}
let password = shuffle(passwordArray).join(""),
passwordStrengthCheck = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
if (password.match(passwordStrengthCheck)) {
return console.log(`Your password is: ${password}`);
} else {
console.log("Failed to generate a strong enough password");
}
}