我正在尝试构建一个密码生成器,它创建的密码符合:
- 最少 8 个字符,最多 40 个字符
- 必须包含至少 1 个大写、小写、数字和符号
我避免选择 Math.random,我更喜欢加密选项。
我已经阅读了大量文章来尝试使其正常工作,但我遇到了以下问题:
随机空格似乎出现在输出字符串中,通常出现在末尾。
输出值有时不符合 min 8 char 规则。
我意识到我可能有太多额外的 if 语句仔细检查了事情,但我很难看出哪里出了问题。
这是为了进入另一个系统,所以我将它创建为尽可能模块化和功能性。为下面的大片段道歉,我无法让它工作jsfiddle.
function cryptoPassword(){
var minFieldNum = 8; //Minimum char size of desired output
var maxFieldNum = 40; //X defines their fields as 40 as the max_length
var outputValue = ''; //Output for field/overall function
var fieldRandom = getRandomInt(minFieldNum, maxFieldNum); //Generate length of password
if (fieldRandom < minFieldNum || fieldRandom > maxFieldNum) {
fieldRandom = getRandomInt(minFieldNum, maxFieldNum); //Regenerate if length doesn't conform - Not working?
}
else {
for (i = 0; outputValue.length < fieldRandom; i++) {
var mask = getRandomMask(); //Get mask selection
var randomChar = mask.charAt(getRandomInt(0,mask.length)); //Pick random char in mask
if (randomChar == " ") { //I don't know where the spaces come from
var randomChar = mask.charAt(getRandomInt(0,mask.length)); //Pick random char in mask
}
outputValue += randomChar; //Add to output
}
if (passwordChecker(outputValue, minFieldNum)) {
return outputValue + " " + passwordChecker(outputValue, minFieldNum);
}
else {
return cryptoPassword();
}
}
}
function getRandomInt(min, max) {
var byteArray = new Uint8Array(1);
window.crypto.getRandomValues(byteArray);
var range = (max - min + 1);
return min + (byteArray[0] % range);
}
function getRandomMask() {
var maskLcaseChar = 'abcdefghijklmnopqrstuvwxyz';
var maskUcaseChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var maskNumeric = '0123456789';
var maskSpecial = '!"$%^&*(){}[];#,./:@~<>?|_+-=';
var maskRandomNo = getRandomInt(0, 3);
var selectMask = [maskLcaseChar, maskUcaseChar, maskNumeric, maskSpecial];
return selectMask[maskRandomNo];
}
function passwordChecker(output, minSize){
var checkChars = '!"$%^&*(){}[];#,./:@~<>?|_+-=';
if (output.length < minSize){
return false
}
else if((output.toUpperCase() != output) && (output.toLowerCase() != output)) {
for (var i = 0; i < output.length; i++) {
if (checkChars.indexOf(output.charAt(i)) != -1) {
return true;
}
}
}
return false;
}