在註冊或會員系統中,我們偶爾需要為使用者產生一組臨時的隨機密碼。透過 JavaScript 便能實現,以下把它封裝成一個可直接掛在 jQuery 上的小工具方法。
做法是利用 Math.random() 產生 33~126 之間的 ASCII 碼,再透過 String.fromCharCode() 轉成字元;若不需要特殊符號,則過濾掉符號所在的區段即可。
$.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 位、含特殊符號
呼叫時只要傳入期望的長度,第二個參數控制是否包含特殊符號。若要用於真正的安全場景(例如加密相關),仍建議改用瀏覽器內建的 window.crypto.getRandomValues(),因為 Math.random() 並非密碼學安全的亂數來源。