Home  >  Article  >  Web Front-end  >  JS密码生成与强度检测完整实例(附demo源码下载)

JS密码生成与强度检测完整实例(附demo源码下载)

WBOY
WBOYOriginal
2018-09-27 10:33:331552browse

本文实例讲述了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(&#39;密码至少4位!&#39;);
    return;
  }
  var o = checkPwd(p);
  if(o.isSame)
  {
    showError(&#39;密码为重复字符!&#39;);
    return;
  }
  for(var i=0; i1900 && year0 && month0 && day<32)
      {
        showError(&#39;不要使用日期作为密码!&#39;);
        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 = &#39;密码长度:&#39; + p.length + &#39; 强度:&#39; + pwdNum + &#39; 预计破解用时:&#39; + formatTime(num / (1024*1024*1024*2.4*2));
  var span1 = document.getElementById(&#39;span1&#39;);
  span1.style.color = &#39;blue&#39;;
  span1.innerHTML = str;
}

4. 检测键盘是否大写锁定(Caps Lock键状态)

截图如下:

相关代码如下:

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);
 }
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn