The example in this article describes the method of JS password generation and strength detection. Share it with everyone for your reference, the details are as follows:
1. Generate a strong password
The screenshot is as follows:
The relevant codes are as follows:
function getPwd(n) { var s = ''; while(n--) s += String.fromCharCode(33 + Math.floor(Math.random()*(126-33))) document.getElementById('txt1').value = s; }
2. Calculate the password cracking time
The screenshot is as follows:
The relevant code is as follows:
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. Password security detection
The screenshot is as follows:
The relevant code is as follows:
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; }
4. Detect whether the keyboard is caps locked (Caps Lock key status)
The screenshot is as follows:
The relevant code is as follows:
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); } }