本文實例講述了JS密碼產生與強度偵測的方法。分享給大家參考,如下:
1. 產生強密碼
截圖如下:
相關代碼如下:function getPwd(n) { var s = ''; while(n--) s += String.fromCharCode(33 + Math.floor(Math.random()*(126-33))) document.getElementById('txt1').value = s; }
2.計算密碼破解時間
截圖如下:截圖如下:
function getTime() { var str = '预计破解用时:'; var selChar = document.getElementById('selChar'); var txtPwdLen = document.getElementById('txtPwdLen'); var num = Math.pow(parseInt(selChar.value), parseInt(txtPwdLen.value)); str += formatTime(num / (1024*1024*1024*2.4*2)); document.getElementById('span2').innerHTML = str; } function formatTime(s) { var str = ''; if(s= 1) str = s % 60 + '秒' + str; s = Math.floor(s / 60); if(s >= 1) str = s % 60 + '分' + str; s = Math.floor(s / 60); if(s >= 1) str = s % 24 + '时' + str; s = Math.floor(s / 24); if(s >= 1) str = s + '天' + str; return str; }
相關程式碼如下:
3.密碼安全偵測
截圖如下:
function showPwd() { var p = document.getElementById('txt2').value; if(p.length < 4) { showError('密码至少4位!'); return; } var o = checkPwd(p); if(o.isSame) { showError('密码为重复字符!'); return; } for(var i=0; i1900 && year0 && month0 && day<32) { showError('不要使用日期作为密码!'); return; } } } var hasUpper = false; var hasLow = false; var hasNum = false; var hasOther = false; for(var i=0; i=65&&c=97&&c=48&&c<=57)hasNum=true; else hasOther=true; } var pwdNum = 0; if(hasUpper)pwdNum+=26; if(hasLow)pwdNum+=26; if(hasNum)pwdNum+=10; if(hasOther)pwdNum+=32; var num = Math.pow(pwdNum, p.length); var str = '密码长度:' + p.length + ' 强度:' + pwdNum + ' 预计破解用时:' + formatTime(num / (1024*1024*1024*2.4*2)); var span1 = document.getElementById('span1'); span1.style.color = 'blue'; span1.innerHTML = str; }
截圖如下:相關程式碼如下:
var $lock = false; function checkCapsLock(fn) { document.documentElement.onkeypress = function(e) { var e = e || event; var k = e.keyCode || e.which; var s = e.shiftKey || (k == 16) || false; if(k>=65&&k=97&&k<=122)$lock=s; fn($lock); } document.documentElement.onkeyup = function(e) { var e = e || event; var k = e.keyCode || e.which; if(k==20)$lock = !$lock; fn($lock); } }