Mr.J--密碼強度檢測
阿新 • • 發佈:2018-11-22
密碼強度,指一個密碼對抗猜測或是暴力破解的有效程度。設定一個高強度的密碼是非常重要的。
javascript核心程式碼
window.onload = function() { var PasswordInput = document.getElementById('password'); PasswordInput.value = ''; var sp = document.getElementsByTagName('span'); PasswordInput.onkeyup = function() { //強度狀態設為預設 sp[0].className = sp[1].className = sp[2].className = "default"; var pwd = this.value; var result = 0; for(var i = 0, len = pwd.length; i < len; ++i) { result |= charType(pwd.charCodeAt(i)); //返回pwd第i位的Unicode編碼 } var PasswordLevel = 0; //對result進行四次迴圈,計算其PasswordLevel for(var i = 0; i <= 4; i++) { if(result & 1) { PasswordLevel++; } //右移一位 result = result >>> 1; } if(pwd.length >= 6) { //當輸入的密碼大於6位,進行判斷,switch判斷密碼強度並展示 switch(PasswordLevel) { case 1: sp[0].className = "weak"; break; case 2: sp[0].className = "medium"; sp[1].className = "medium"; break; case 3: case 4: sp[0].className = "strong"; sp[1].className = "strong"; sp[2].className = "strong"; break; } } } } function charType(num) { //函式返回值返回在強度檢測switch裡面 if(num >= 48 && num <= 57) { return 1; } if(num >= 97 && num <= 122) { return 2; } if(num >= 65 && num <= 90) { return 4; } return 8; }
html:
效果圖: