如何使这个随机密码生成器生成至少一个组件? 目前,生成的密码中不包含数字,或者省略任何其他类型。如何让它生成至少一种类型?
$scope.passwordLength = 12;
$scope.addUpper = true;
$scope.addNumbers = true;
$scope.addSymbols = true;
$scope.createPassword = function(){
var lowerCharacters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var upperCharacters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
var numbers = ['0','1','2','3','4','5','6','7','8','9'];
var symbols = ['!', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'];
var finalCharacters = lowerCharacters;
if($scope.addUpper){
finalCharacters = finalCharacters.concat(upperCharacters);
}
if($scope.addNumbers){
finalCharacters = finalCharacters.concat(numbers);
}
if($scope.addSymbols){
finalCharacters = finalCharacters.concat(symbols);
}
var passwordArray = [];
for (var i = 1; i < $scope.passwordLength; i++) {
passwordArray.push(finalCharacters[Math.floor(Math.random() * finalCharacters.length)]);
};
$scope.password = passwordArray.join("");
};
答案 0 :(得分:6)
您正在做的是创建所有可能字符的数组(finalCharacters
)并随机取12个字符。
您需要做的是从每个所需数组中取一个随机字符(upperCharacters
,numbers
,symbols
)并将其随机播放。
算法示例:
lowerCharacters
,upperCharacters
,...)中的适当数量的随机字符推入数组(即passwordArray
)passwordArray
passwordArray
第一步可能是:
noOfLowerCharacters = 0
,noOfUpperCharacters = 0
,noOfUpperCharacters = 0
1
,2
或3
)。将其存储在变量noOfneededTypes
。1
到(passwordLength
- noOfneededTypes
)的范围内取随机数。将其存储在变量noOfLowerCharacters
中。 usedTypeCounter
。将值设置为1
addUpper
,则从1
到{passwordLength
- noOfneededTypes
+ usedTypeCounter
- noOfLowerCharacters
的范围内随机抽取数字。将其存储在变量noOfUpperCharacters
中。增加usedTypeCounter
addNumbers
则从1
到{passwordLength
- noOfneededTypes
+ usedTypeCounter
- noOfLowerCharacters
- {{1 }})。将其存储在变量noOfUpperCharacters
中。 noOfNumbers
则addSymbols
= noOfSymbols
- passwordLength
- noOfLowerCharacters
- noOfUpperCharacters
实施示例:
noOfNumbers
答案 1 :(得分:2)
您还可以创建随机密码,直到其中一个符合您的条件:
function randomPass (length, addUpper, addSymbols, addNums) {
var lower = "abcdefghijklmnopqrstuvwxyz";
var upper = addUpper ? lower.toUpperCase() : "";
var nums = addNums ? "0123456789" : "";
var symbols = addSymbols ? "!#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~" : "";
var all = lower + upper + nums + symbols;
while (true) {
var pass = "";
for (var i=0; i<length; i++) {
pass += all[Math.random() * all.length | 0];
}
// criteria:
if (!/[a-z]/.test(pass)) continue; // lowercase is a must
if (addUpper && !/[A-Z]/.test(pass)) continue; // check uppercase
if (addSymbols && !/\W/.test(pass)) continue; // check symbols
if (addNums && !/\d/.test(pass)) continue; // check nums
return pass; // all good
}
}
答案 2 :(得分:2)
答案 3 :(得分:1)