脚本使用JavaScript生成大小写数字和符号的密码



我使用这个脚本在zapier上生成密码。它工作得很好,但我发现它有时会生成没有数字的密码。你能给我做个现场演示吗

function generateP() {
var pass = '';
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '1234567890' + '!@#$%^&()_+~`|}{[]:;?><,./-=';
for (var i = 1; i <= 16; i++) {
var char = Math.floor(Math.random() * str.length + 1);
pass += str.charAt(char)
}
return pass;
}
console.log(generateP())

从所有组中随机取一个大写字母,一个小写字母,一个随机数字,一个随机符号和12个随机字符。洗牌(我已经从如何随机化(洗牌)一个JavaScript数组中复制了洗牌函数)

function getRandomChar(str) {
return str.charAt(Math.floor(Math.random() * str.length));
}
function shuffle(array) {
var currentIndex = array.length,  randomIndex;
// While there remain elements to shuffle...
while (currentIndex != 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
function generateP(options) {
const groups = options?.groups ?? [
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz',
'1234567890',
'!@#$%^&()_+~`|}{[]:;?><,./-='
];
const length = options?.length ?? 16;
let pass = groups.map(getRandomChar).join('');

const str = groups.join('');

for (let i = pass.length; i <= length; i++) {
pass += getRandomChar(str)
}
return shuffle(pass);
}
console.log(generateP());
// Tests
console.log('Running tests...');
for (let i = 0; i < 1e5; ++i) {
const pass = generateP();
if (!/[A-Z]/.test(pass) || !/[a-z]/.test(pass) || !/[0-9]/.test(pass) || !/[!@#$%^&()_+~`|}{[]:;?><,./-=]/.test(pass)) {
console.log('generateP() failed with: ' + pass);
}
}
console.log('Tests finished');

下面的代码符合您的要求:

var fpwd = "";
var lpwd = 16;
for (;;) {
var rnd = Math.floor(Math.random() * 128);
if (rnd >= 33 && rnd <= 126) {
fpwd += String.fromCharCode(rnd);
}
if (fpwd.length == lpwd) {
if (fpwd.match(/(?=.*d)(?=.*[a-z])(?=.*[A-Z])((?=.*W)|(?=.*_))^[^ ]+$/g)) {
break;
} else {
fpwd = "";
}
}
}
console.log(fpwd);

最新更新