Python实现的密码强度检测器示例


Posted in Python onAugust 23, 2017

本文实例讲述了Python实现的密码强度检测器。分享给大家供大家参考,具体如下:

密码强度

密码强度如何量化呢?

一个密码可以有以下几种类型:长度、大写字母、小写字母、数字以及特殊符号。

显然,密码包含的特征越多、长度越长,其强度也就越高。

我们设置几个等级来评测密码强度,分别是:terrible, simple,
medium, strong

不同的应用可能对密码强度的要求不一样,我们引入最小程度(min_length)和最小特征数(min_types),作为可配置选项。

这样我们就可以检测密码包含的特征,特征与密码之间的关系可以简单定义为:

特征数 强度
小于最小长度 terrible
常用密码或规则的密码 simple
小于最小特征数 medium
大于或等于最小特征数 strong

另:常用的1万个密码点击此处本站下载

代码实现

check.py

# coding: utf-8
"""
check
Check if your password safe
"""
import re
# 特征
NUMBER = re.compile(r'[0-9]')
LOWER_CASE = re.compile(r'[a-z]')
UPPER_CASE = re.compile(r'[A-Z]')
OTHERS = re.compile(r'[^0-9A-Za-z]')
def load_common_password():
 words = []
 with open("10k_most_common.txt", "r") as f:
  for word in f:
   words.append(word.strip())
 return words
COMMON_WORDS = load_common_password()
# 管理密码强度的类
class Strength(object):
 """
 密码强度三个属性:是否有效valid, 强度strength, 提示信息message
 """
 def __init__(self, valid, strength, message):
  self.valid = valid
  self.strength = strength
  self.message = message
 def __repr__(self):
  return self.strength
 def __str__(self):
  return self.message
 def __bool__(self):
  return self.valid
class Password(object):
 TERRIBLE = 0
 SIMPLE = 1
 MEDIUM = 2
 STRONG = 3
 @staticmethod
 def is_regular(input):
  regular = ''.join(['qwertyuiop', 'asdfghjkl', 'zxcvbnm'])
  return input in regular or input[::-1] in regular
 @staticmethod
 def is_by_step(input):
  delta = ord(input[1]) - ord(input[0])
  for i in range(2, len(input)):
   if ord(input[i]) - ord(input[i - 1]) != delta:
    return False
  return True
 @staticmethod
 def is_common(input):
  return input in COMMON_WORDS
 def __call__(self, input, min_length=6, min_type=3, level=STRONG):
  if len(input) < min_length:
   return Strength(False, "terrible", "密码太短了")
  if self.is_regular(input) or self.is_by_step(input):
   return Strength(False, "simple", "密码有规则")
  if self.is_common(input):
   return Strength(False, "simple", "密码很常见")
  types = 0
  if NUMBER.search(input):
   types += 1
  if LOWER_CASE.search(input):
   types += 1
  if UPPER_CASE.search(input):
   types += 1
  if OTHERS.search(input):
   types += 1
  if types < 2:
   return Strength(level <= self.SIMPLE, "simple", "密码太简单了")
  if types < min_type:
   return Strength(level <= self.MEDIUM, "medium", "密码还不够强")
  return Strength(True, "strong", "密码很强")
class Email(object):
 def __init__(self, email):
  self.email = email
 def is_valid_email(self):
  if re.match("^.+@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", self.email):
   return True
  return False
 def get_email_type(self):
  types = ['qq', '163', 'gmail', '126', 'sina']
  email_type = re.search('@\w+', self.email).group()[1:]
  if email_type in types:
   return email_type
  return 'wrong email'
password = Password()

test_check.py: 用于单元测试

# coding: utf-8
"""
test for check
"""
import unittest
import check
class TestCheck(unittest.TestCase):
 def test_regular(self):
  rv = check.password("qwerty")
  self.assertTrue(repr(rv) == "simple")
  self.assertTrue('规则' in rv.message)
 def test_by_step(self):
  rv = check.password("abcdefg")
  self.assertTrue(repr(rv) == "simple")
  self.assertTrue('规则' in rv.message)
 def test_common(self):
  rv = check.password("password")
  self.assertTrue(repr(rv) == "simple")
  self.assertTrue('常见' in rv.message)
 def test_medium(self):
  rv = check.password("ahj01a")
  self.assertTrue(repr(rv) == 'medium')
  self.assertTrue('不够强' in rv.message)
 def test_strong(self):
  rv = check.password("asjka9AD")
  self.assertTrue(repr(rv) == 'strong')
  self.assertTrue('很强' in rv.message)
 # 测试邮箱
 def test_email(self):
  rv = check.Email("123@gmail.com")
  self.assertEqual(rv.is_valid_email(), True)
 def test_email_type(self):
  rv = check.Email("123@gmail.com")
  types = ['qq', '163', 'gmail', '126', 'sina']
  self.assertIn(rv.get_email_type(), types)
if __name__ == '__main__':
 unittest.main()
Python 相关文章推荐
21行Python代码实现拼写检查器
Jan 25 Python
python实时分析日志的一个小脚本分享
May 07 Python
pandas数据分组和聚合操作方法
Apr 11 Python
Python采集猫眼两万条数据 对《无名之辈》影评进行分析
Dec 05 Python
python 画三维图像 曲面图和散点图的示例
Dec 29 Python
在python中获取div的文本内容并和想定结果进行对比详解
Jan 02 Python
python 模拟创建seafile 目录操作示例
Sep 26 Python
python 字典有序并写入json文件过程解析
Sep 30 Python
使用python 对验证码图片进行降噪处理
Dec 18 Python
opencv中图像叠加/图像融合/按位操作的实现
Apr 01 Python
Numpy 理解ndarray对象的示例代码
Apr 03 Python
Python实现AI换脸功能
Apr 10 Python
python+selenium+autoit实现文件上传功能
Aug 23 #Python
Django与JS交互的示例代码
Aug 23 #Python
python paramiko模块学习分享
Aug 23 #Python
定制FileField中的上传文件名称实例
Aug 23 #Python
基于python元祖与字典与集合的粗浅认识
Aug 23 #Python
Python 多线程Threading初学教程
Aug 22 #Python
Python3实现抓取javascript动态生成的html网页功能示例
Aug 22 #Python
You might like
Ajax提交表单时验证码自动验证 php后端验证码检测
2016/07/20 PHP
PHP面试常用算法(推荐)
2016/07/22 PHP
PHP网站常见安全漏洞,及相应防范措施总结
2021/03/01 PHP
为jQuery增加join方法的实现代码
2010/11/28 Javascript
javascript实现文本域写入字符时限定字数
2014/02/12 Javascript
Js实现网页键盘控制翻页的方法
2014/10/30 Javascript
jQuery Masonry瀑布流插件使用详解
2014/11/17 Javascript
深入解析JavaScript编程中的this关键字使用
2015/11/09 Javascript
基于javascript html5实现3D翻书特效
2016/03/14 Javascript
jQuery插件FusionCharts实现的2D柱状图效果示例【附demo源码下载】
2017/03/06 Javascript
Require.JS中的几种define定义方式示例
2017/06/01 Javascript
关于Stream和Buffer的相互转换详解
2017/07/26 Javascript
elementUI 设置input的只读或禁用的方法
2018/10/30 Javascript
js实现聊天对话框
2020/02/08 Javascript
[39:11]DOTA2上海特级锦标赛C组资格赛#2 LGD VS Newbee第二局
2016/02/28 DOTA
[07:25]DOTA2-DPC中国联赛2月5日Recap集锦
2021/03/11 DOTA
Python实现partial改变方法默认参数
2014/08/18 Python
python中实现php的var_dump函数功能
2015/01/21 Python
Python RuntimeError: thread.__init__() not called解决方法
2015/04/28 Python
详解Python中open()函数指定文件打开方式的用法
2016/06/04 Python
Python编程实现的简单Web服务器示例
2017/06/22 Python
Python科学画图代码分享
2017/11/29 Python
python调用c++返回带成员指针的类指针实例
2019/12/12 Python
python中取绝对值简单方法总结
2020/07/24 Python
详解纯CSS3制作的20种loading动效
2017/07/05 HTML / CSS
CSS3使用border-radius属性制作圆角
2014/12/22 HTML / CSS
Haggar官网:美国男装品牌
2020/02/16 全球购物
Herschel Supply Co.美国:背包、手提袋及配件
2020/11/24 全球购物
final, finally, finalize的区别
2012/03/01 面试题
民主评议政风行风整改方案
2014/09/17 职场文书
防火标语大全
2014/10/06 职场文书
新教师教学工作总结
2015/08/12 职场文书
男方家长婚礼答谢词
2015/09/29 职场文书
2016年党支部公开承诺书
2016/03/25 职场文书
应用最多的公文《通知》如何写?
2019/04/02 职场文书
Python-OpenCV教程之图像的位运算详解
2021/06/21 Python