Python实现的密码强度检测器示例
本文介绍了一个使用Python实现的密码强度检测器。该检测器通过正则表达式判断密码是否包含数字、大小写字母及特殊符号,并结合长度、常见密码和规则密码(如连续字符)来评估密码强度。文章提供了完整的代码实现及单元测试示例,帮助开发者快速集成密码安全校验功能。
密码强度检测器实现原理
密码强度的评估通常基于长度、字符类型多样性以及是否属于常见或规则密码。该检测器将强度分为四个等级:terrible(极弱)、simple(简单)、medium(中等)和 strong(强)。其核心逻辑如下:
- 长度不足时,直接判定为 terrible。
- 包含常见密码或规则密码(如连续键盘字符)时,判定为 simple。
- 特征数(数字、大小写、特殊符号)不足时,判定为 medium。
- 特征数达标且长度足够时,判定为 strong。
核心代码实现
检测器使用 re 模块定义正则表达式来匹配不同类型的字符。同时,通过加载常见密码列表(如 10k_most_common.txt)来识别弱密码。以下是核心类的实现:
# 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()单元测试示例
为了确保检测器的准确性,可以使用 unittest 模块编写测试用例。以下测试覆盖了规则密码、步进密码、常见密码、中等强度和强密码的情况,以及邮箱验证功能:
# 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()总结
该密码强度检测器通过结合长度、字符类型、常见密码和规则密码的判断,提供了一个较为全面的密码安全评估方案。开发者可以根据实际需求调整 min_length 和 min_type 参数,以适应不同的安全要求。
以上就是Python实现的密码强度检测器示例的详细内容,更多关于Python密码安全校验的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









