DIV CSS 佈局教程網

用 jQuery 寫一個可指定長度與是否含特殊符號的隨機密碼產生器
編輯:JavaScript綜合知識     

註冊頁面常需要「產生一組建議密碼」的功能。與其每次重新整理頁面,不如做一個按鈕,點一下就換一組。這個範例把它擴充成 jQuery 靜態方法,可指定長度、也能決定要不要包含特殊符號。

程式碼

$.extend({
  password: function (length, special) {
    var iteration = 0;
    var password = "";
    var randomNumber;

    if (special == undefined) {
      var special = false;
    }

    while (iteration < length) {
      randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;

      if (!special) {
        // 排除特殊符號所在的區段
        if ((randomNumber >= 33)  && (randomNumber <= 47))  { continue; }
        if ((randomNumber >= 58)  && (randomNumber <= 64))  { continue; }
        if ((randomNumber >= 91)  && (randomNumber <= 96))  { continue; }
        if ((randomNumber >= 123) && (randomNumber <= 126)) { continue; }
      }

      iteration++;
      password += String.fromCharCode(randomNumber);
    }
    return password;
  }
});

// 使用方式
$.password(8);        // 8 位、不含特殊符號
$.password(12, true); // 12 位、含特殊符號

它是怎麼運作的

$.extend({...}) 把函式掛到 jQuery 物件上,形成 $.password() 這種靜態呼叫,跟 $.inArray() 是同一種寫法。

核心在 String.fromCharCode():ASCII 從 33 到 126 是「所有可列印的 ASCII 字元」,包含數字、大小寫字母與符號。程式先產生 33~126 之間的亂數,再依 special 參數決定要不要跳過符號所在的幾個區段(33-47、58-64、91-96、123-126)。用 continue 跳過而不遞增 iteration,才能確保最終長度正好是 length。

安全性上的建議

這個寫法教學價值高,但若要用在真正的帳號系統,有兩點必須補強。

第一,Math.random() 不是密碼學安全的亂數來源,它的內部狀態可被推導,產生的密碼具備預測性。應該改用 window.crypto.getRandomValues()(瀏覽器端)或 crypto.randomBytes()(Node.js)。

第二,純隨機產生的密碼往往不符合「至少一個大寫、一個數字、一個符號」這類系統規則,也可能剛好不含任何數字。實務上會先從各類別各取一個字元,剩餘位數再隨機填滿後打亂順序,並過濾掉容易混淆的字元(如 0 與 O、1 與 l)。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved