簡體   English   中英

為什么我用 JavaScript 編寫的密碼生成器經常返回帶有重復字符的密碼?

[英]Why does my password generator written in JavaScript often return passwords with repeating characters?

我寫了一個 JavaScript class 和四個 static 變量,包含最終密碼可能包含的不同種類的字符。 class 包含四個 getter 函數,它們從這四個變量返回一個隨機字符。 在單獨的 function 中,我嘗試創建密碼。 不幸的是,最終密碼似乎並不包含完全隨機的字符。 通常重復相同的字符。

我仔細查看了我的隨機函數,但它似乎沒問題。 我希望您知道為什么密碼最終如此相似,例如 AAAh^8 或 bSS+5S

class Password{
    
    static lowerCase = "abcdefghijklmnopqrstuvwxyz";
    static upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    static numbers   = "0123456789";
    static symbols   = "!@#$%^&*()_+~\\`|}{[]:;?><,./-=";

    length = document.getElementById("passwordLength").value;

    getKey = [this.upperCase, this.lowerCase, this.num, this.symbol]

    get upperCase(){
        return Password.upperCase[Math.floor(Math.random() * Password.upperCase.length)]
        }
    get lowerCase(){
        return Password.lowerCase[Math.floor(Math.random() * Password.lowerCase.length)]
    }
    get num(){
        return Password.numbers[Math.floor(Math.random() * Password.numbers.length)]
    }
    get symbol(){
        return Password.symbols[Math.floor(Math.random() * Password.symbols.length)]
    }
    password = ""
}

function createPassword(){
    const newPass = new Password;
     
    for (var i=0; i<newPass.length; i++){
        key = newPass.getKey[Math.floor(Math.random() * newPass.getKey.length)]
        newPass.password += key
        console.log("Random Key Run " + i + ": " + key)
    }
    console.log("Final Password: " + newPass.password)
}
createPassword()

正如@deceze 所說,您實際上是在getKey初始值設定項中預先選擇了 4 個不同的字符。

如果你不那么喜歡吸氣劑,你可能會有更好的時間,例如

function pick(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

class PasswordGenerator {
  static lowerCase = "abcdefghijklmnopqrstuvwxyz";
  static upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  static numbers = "0123456789";
  static symbols = "!@#$%^&*()_+~\\`|}{[]:;?><,./-=";
  static classes = [
    PasswordGenerator.lowerCase,
    PasswordGenerator.upperCase,
    PasswordGenerator.numbers,
    PasswordGenerator.symbols,
  ];

  getChar() {
    const cls = pick(PasswordGenerator.classes);
    return pick(cls);
  }
}

function createPassword() {
  const generator = new PasswordGenerator();
  let password = "";
  for (var i = 0; i < 8; i++) {
    const key = generator.getChar();
    password += key;
    console.log(`Random Key Run ${i}: ${key}`);
  }
  console.log("Final Password: " + password);
}

createPassword();

我還冒昧地將不一定是Password state 的內容從PasswordGenerator生成器 class 中移出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM