Javascript 用户输入密码生成器?

Javascript user input password generator?

对于学校,我的任务是创建一个密码生成器,通过确认提示用户他们是否需要密码中的大写、小写、数字和符号以及 8-128 个字符。到目前为止,我已经为大写字母、小写字母、数字和符号创建了数组。

    var uppercase = ["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 lowercase = ["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 = ["!", "#", "$", "&", "%", "'", "(", ")", "*", "+", "-", "/", ":", ";", "<", "=", ">", "?", "@", "^", "_", "~", "`", "{", "|", "}", "."];

除此之外,我还为他们创建了确认消息,但我不确定如何将两者联系起来,然后根据他们的回复随机生成密码。

让我们试着制定一个计划:

您有 4 个字符集。 你有用户的答案。

根据他的回答,您将尝试填充一组可用的集合。我们称它为 availableCollections。如果用户需要这组字符,该数组将包含您已有的其他数组。

用户想要大写字符?在 availableCollections.

中推送 uppercase 数组

对其他数组执行相同的操作。

那我们定义一个空字符串来存放密码。我们将其命名为 password


现在让我们随机获取一个角色。首先,您需要随机 select 那些 availableCollections。所以你想找到一个函数来从 availableCollections 中检索随机项目。我们称此项目为 randomCollection。 此 randomCollection 是您之前定义的包含一组字符的数组之一。 (uppercase, lowercase, numbers, symbols)

您想 select 从 randomCollection 中随机抽取一个字符。使用与上面相同的方法。我们称这个角色为 randomCharacter.

您现在可以将此 randomCharacterpassword 字符串连接起来。


要生成完整密码,您只需循环执行此任务以生成所需数量的字符。

这是一种方法。

const PASSWORD_LENGTH = 20;

const uppercase = ["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"];
const lowercase = ["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"];
const numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
const symbols = ["!", "#", "$", "&", "%", "'", "(", ")", "*", "+", "-", "/", ":", ";", "<", "=", ">", "?", "@", "^", "_", "~", "`", "{", "|", "}", "."];


function generatePassword(useUpper, useLower, useNumbers, useSymbols)
{
  return []
    .reduce((collection, item) => {
      if (useUpper) collection.push(item);
      return collection;
    }, uppercase)
    .reduce((collection, item) => {
      if (useLower) collection.push(item);
      return collection;
    }, lowercase)
    .reduce((collection, item) => {
      if (useNumbers) collection.push(item);
      return collection;
    }, numbers)
    .reduce((collection, item) => {
      if (useSymbols) collection.push(item);
      return collection;
    }, symbols)
    .sort(() => Math.random() - 0.5)
    .slice(0, PASSWORD_LENGTH)
    .join('');
}

console.log(generatePassword(true, true, true, true));
console.log(generatePassword(true, false, false, true));

现在的步骤,我们使用布尔类型指示器(useUpper, useLower, useNumbers, useSymbols)来告诉我们需要将哪些数组加在一起。

我们遍历每个可能的数组以允许链接,if (use%%%) collection.append 只是将项目添加到我们的字符集合中。可能有一堆条件,但这需要我们改变数组。

.reduce((collection, item) => {
  if (useUpper) collection.push(item);
  return collection;
}, uppercase)

追加所有需要的项目后,我们看到对数组排序方法的调用,.sort(() => Math.random() - 0.5)这只是随机排列数组,所以我们不会得到相同的字符序列。

然后我们 slice 从索引 0 开始并等于 PASSWORD_LENGTH 的长度的部分数组。

然后我们只需 join 数组和一个空字符串分隔符,我们现在就有了密码。

请注意,这远非最有效的解决方案。

生成密码示例代码:

function gen_pass()
{


var uppercase = document.getElementById("uppercase").checked === true ? true : false;
var lowercase = document.getElementById("lowercase").checked === true ? true : false;
var numbers = document.getElementById("numbers").checked === true ? true : false;
var symbols = document.getElementById("symbols").checked === true ? true : false;
var len = document.getElementById("len").value;


var str= [ ["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"],
["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"],
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
["!", "#", "$", "&", "%", "'", "(", ")", "*", "+", "-", "/", ":", ";", "<", "=", ">", "?", "@", "^", "_", "~", "`", "{", "|", "}", "."]];
var str_user;
uppercase===true ? str_user=str[0] :0;
lowercase===true ? str_user+=str[1] :0;
numbers===true ? str_user+=str[2] :0;
symbols===true ? str_user+=str[3] :0;
if(str_user){
  let len_str =  str_user.length;
  var v= Math.floor(Math.random() * str_user.length);
  var password = str_user[v];

  for (let i = 0 ; i<len ; i++ )
  { 
    v= Math.floor(Math.random() * str_user.length);
    console.log(v);
    password += str_user[v];
  }
  console.log(password);
  document.getElementById("password").value =password;
}else{
 
  alert('Minmum check mark 1 option for generation password');

}
}
<html>
<body>
uppercase: <input type="checkbox" id="uppercase">
<br>
lowercase: <input type="checkbox" id="lowercase">
<br>
numbers: <input type="checkbox" id="numbers">
<br>
symbols: <input type="checkbox" id="symbols">
<br>
<input type="number" id="len" value="8" >
<br>
<button onclick="gen_pass()">Genrate Password</button>
<br><br>
<input type="text" id="password" value="">
</body>
</html>

秘密就在我的 PassGen 构造函数中。试一试!

//<![CDATA[
/* js/external.js */
let get, post, doc, html, bod, nav, M, I, mobile, S, Q, aC, rC, tC, shuffle, rand, PassGen; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
  const x = new XMLHttpRequest;
  const c = context || x;
  x.open('GET', url);
  x.onload = ()=>{
    if(success)success.call(c, JSON.parse(x.responseText));
  }
  x.send();
}
post = function(url, send, success, context){
  const x = new XMLHttpRequest;
  const c = context || x;
  x.open('POST', url);
  x.onload = ()=>{
    if(success)success.call(c, JSON.parse(x.responseText));
  }
  if(typeof send === 'object' && send && !(send instanceof Array)){
    if(send instanceof FormData){
      x.send(send);
    }
    else{
      const fd = new FormData;
      for(let k in send){
        fd.append(k, JSON.stringify(send[k]));
      }
      x.send(fd);
    }
  }
  else{
    throw new Error('send argument must be an Object');
  }
  return x;
}
doc = document; html = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
  var w = within || doc;
  return w.querySelector(selector);
}
Q = (selector, within)=>{
  var w = within || doc;
  return w.querySelectorAll(selector);
}
aC = function(){
  const a = [].slice.call(arguments), n = a.shift();
  n.classList.add(...a);
  return aC;
}
rC = function(){
  const a = [].slice.call(arguments), n = a.shift();
  n.classList.remove(...a);
  return rC;
}
tC = function(){
  const a = [].slice.call(arguments), n = a.shift();
  n.classList.toggle(...a);
  return tC;
}
shuffle = array=>{
  let a = array.slice(), i = a.length, n, h;
  while(i){
    n = Math.floor(Math.random()*i--); h = a[i]; a[i] = a[n]; a[n] = h;
  }
  return a;
}
rand = (min, max)=>{
  let mn = min, mx = max;
  if(mx === undefined){
    mx = mn; mn = 0;
  }
  return mn+Math.floor(Math.random()*(mx-mn+1));
}
PassGen = function(special = '!@#$%^&*-+/=_?'){
  const abc = 'abcdefghijklmnopqrstuvwxyz';
  const az = abc.split(''), aZ = abc.toUpperCase().split(''), aL = az.length-1;
  const sc = special.split(''), sL = sc.length-1;
  let gen = '';
  this.numbers = count=>{
    for(let i=0; i<count; i++){
      gen += rand(9).toString();
    }
    return this;
  }
  this.lowerCases = count=>{
    for(let i=0; i<count; i++){
      gen += az[rand(aL)];
    }
    return this;
  }
  this.upperCases = count=>{
    for(let i=0; i<count; i++){
      gen += aZ[rand(aL)];
    }
    return this;
  }
  this.specials = count=>{
    for(let i=0; i<count; i++){
      gen += sc[rand(sL)];
    }
    return this;
  }
  this.generate = ()=>{
    const g = shuffle(gen.split('')).join('');
    gen = '';
    return g;
  }
}
// you can put the following on another page using a load Event - besides the end load
const user = I('user'), pass = I('pass'), pass_match = I('pass_match'), gen = I('gen');
const pg = new PassGen("!#$&%]'()*+-/:;<=>?@^_~`{|}."), choose = I('choose');
const generate = I('generate'), login = I('login'), uc = I('uc'), lc = I('lc');
const no = I('no'), sc = I('sc');
let see = false;
user.value = pass.value = ''; uc.value = lc.value = no.value = sc.value = '2';
user.onfocus = pass.onfocus = pass_match.onfocus = ()=>{
  pass.type = pass_match.type = 'password'; aC(choose, 'hid'); see = false;
}
user.oninput = pass.oninput = pass_match.oninput = function(){
  let f = this.value !== '' ? aC : rC;
  let p = pass.value, m = pass_match.value, r;
  f(this, 'good');
  if(user.value === '' || p === '' || m === '' || p !== m){
    f = aC;
    r = p === m && p !== '' ? aC : rC;
  }
  else if(p === m){
    r = aC; f = rC;
  }
  r(pass, 'good'); r(pass_match, 'good'); f(login, 'hid');
}
gen.onclick = ()=>{
  let f, p = pass.value, m = pass_match.value;
  if(see){
    aC(choose, 'hid'); f = rC; pass.type = pass_match.type = 'password';
  }
  else{
    rC(choose, 'hid'); f = aC; pass.type = pass_match.type = 'text';
    generate.focus();
  } 
  if(user.value === '' || p === '' || m === '' || p !== m)f = aC;
  f(login, 'hid'); see = !see;
}
uc.oninput = lc.oninput = no.oninput = sc.oninput = function(){
  const v = this.value, n = +v, c = +uc.value+(+lc.value)+(+no.value)+(+sc.value);
  let f, r;
  if(v.match(/^(0|[1-9][0-9]*)$/) && c < 129 && c > 7){
    f = aC; r = rC;
  }
  else{
    f = rC; r = aC;
  }
  f(this, 'good'); r(generate, 'hid');
}
generate.onclick = ()=>{
  pass.value = pass_match.value = pg.upperCases(+uc.value).lowerCases(+lc.value).numbers(+no.value).specials(+sc.value).generate();
  aC(pass, 'good'); aC(pass_match, 'good'); aC(choose, 'hid'); see = false;
  if(user.value !== '')rC(login, 'hid');
}
login.onclick = ()=>{
  console.log('AJAX here');
}
}); // end load
//]]>
/* css/external.css */
*{
  box-sizing:border-box; padding:0; margin:0; font-size:0; overflow:hidden;
}
html,body,.main{
  width:100%; height:100%; background:#ccc;
}
.main{
  padding:10px; overflow-y:scroll;
}
#inc,#dec{
  width:20px;
}
label,input,textarea{
  font:bold 22px Tahoma, Geneva, sans-serif;  border-radius:3px;
}
input,textarea,select{
   width:100%; padding:3px 5px; border:1px solid #b00;
}
label{
  display:inline-block; cursor:pointer; margin-top:2px;
}
label:first-child{
  margin-top:0;
}
#pass{
  width:90%;
}
#pass_match,#login{
  margin-bottom:10px;
}
input[type=button]{
  background:linear-gradient(#1b7bbb,#147); color:#fff; border:1px solid #147; border-radius:5px; margin-top:7px; cursor:pointer;
}
input[type=button].gen{
  width:10%; margin:0;
}
#choose{
  padding:3px 7px 7px; border:5px solid #1b7bbb; border-radius:4px; margin-top:7px;
}
#login{
  background:linear-gradient(#679467,#235023); border:1px solid #c00; border-color:#050;
}
.hid{
  display:none;
}
.good{
  border-color:#0b0;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
    <title>Title Here</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />
    <script src='js/external.js'></script>
  </head>
<body>
  <div class='main'>
    <label for='user'>Username</label>
    <input id='user' type='text' maxlength='128' value='' />
    <label for='pass'>Password</label><br />
    <input id='pass' type='password' maxlength='128' value='' /><input class='gen' id='gen' type='button' value='!' />
    <label for='pass_match'>Reenter Password</label>
    <input id='pass_match' type='password' maxlength='128' value='' />
    <div class='hid' id='choose'>
      <label for='uc'>Uppercase</label>
      <input class='good' id='uc' type='number' min='0' max='128' value='2' />
      <label for='lc'>Lowercase</label>
      <input class='good' id='lc' type='number' min='0' max='128' value='2' />
      <label class='good' for='no'>Numbers</label>
      <input class='good' id='no' type='number' min='0' max='128' value='2' />
      <label class='good' for='sc'>Special</label>
      <input class='good' id='sc' type='number' min='0' max='128' value='2' />
      <input id='generate' type='button' value='Generate' />
    </div>
    <input class='hid' id='login' type='button' value='Login' />
  </div>
</body>
</html>