【发布时间】:2013-04-28 16:04:05
【问题描述】:
我有这个 javascript 密码生成功能。现在我正在丢弃不符合所选规范的密码。例如,如果密码不包含数字,我会丢弃它并生成一个新的一跳,其中包含一个数字。然而,这似乎不是有效的性能虎钳,至少对我来说不是。
有没有更好的方法来实现生成密码中特定字符的强制?
我还计划添加,以便可以强制密码包含特殊字符。如果我以当前的方式执行此操作,我将不得不使用一些正则表达式来检查密码是否包含特殊字符,如果不包含特殊字符,则将其丢弃(再次对我来说似乎不是很有效)。
function generatePassword(length, charset, nosimilar) {
// default parameters
length = (typeof length === "undefined") ? 8 : length;
charset = (typeof charset === "undefined") ? 'abcdefghjknpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789' : charset;
nosimilar = (typeof similar === "undefined") ? true : nosimilar;
var gen;
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
gen = charset.charAt(Math.floor(Math.random() * n))
if ( (retVal.charAt( retVal.length-1 ) == gen) && (nosimilar)) {
retVal = retVal.substring(0, retVal.length - 1)
retVal += charset.charAt(Math.floor(Math.random() * n))
console.log('Generated character same as the last one. Trunkated and regenerated.');
}
retVal += gen;
}
// if charset contains numbers make sure we get atleast one number
if ( (retVal.match(/\d+/g) == null) && (charset.match(/\d+/g) != null)) {
console.log('Password generated but no numbers found. Regenerating.');
generatePassword(length, charset, nosimilar);
}
return retVal;
}
if ($("#chLetters").prop('checked')) charset += 'abcdefghjknpqrstuvwxyz';
if ($("#chNumbers").prop('checked')) charset += '123456789';
if ($("#chMixedCase").prop('checked')) charset += 'ABCDEFGHJKLMNPQRSTUVWXYZ';
if ($("#chSpecial").prop('checked')) charset += '!@$%&?+*-_';
$("#passgen").text(generatePassword($("#maxLength").val(), charset, $("#chNoSimilar").prop('checked')));
【问题讨论】:
-
您想要的密码可以是完全随机的吗?我知道必须有特殊标志,但还有其他规则吗?特殊符号应该出现在字符串的什么位置?
-
好吧,我会在不同的步骤中使用不同的字符集。示例:小写集、大写集、数字集、特殊集。然后从每个集合中选择元素开始,将它们放在字符串中的随机位置。例如,4 个小写元素,2 个大写字母,2 个数字,1 个特殊元素。
-
这个问题在codereview.stackexchange.com会更好吗?
-
这个想法是将不同的字符集传递给函数,具体取决于密码的外观。如果这个问题更多地属于 codereview,我也存在分歧。不知道,随意移动它。
-
我认为如果主题发生变化,这将更适合这里:例如“如何确保生成的密码符合要求”就可以了。 (尤其是因为关于“效率低下”的问题有点学术性:即使该函数在找到符合规范的密码之前运行一千次,最终用户也不会注意到速度上有任何差异。)
标签: javascript function random passwords