密码强度检测:Python代码实现及示例
密码强度检测:Python代码实现及示例
本文将介绍如何使用Python代码实现密码强度检测,并提供示例代码和运行截图。内容涵盖密码长度、字符类型等因素对强度等级的影响,以及具体的判定逻辑。
密码强度规则
用户输入口令后,请进行强度检测,等级分为三种:强、中、弱。
- 口令长度小于等于8位,并且纯小写英文或大写英文,弱
- 口令长度小于等于8位,并且有小写、大写英文和非英文字符,中
- 口令长度大于8位,并且纯小写英文或大写英文,中
- 口令长度大于8位且小于等于16位,并且有小写英文、大写英文、非英文字符中的两种,中
- 口令长度大于16位,并且有小写英文、大写英文、非英文字符中的两种,强
- 口令长度大于16位,并且有小写英文、大写英文、非英文字符中的三种,强
Python代码实现
import re
def check_password_strength(password):
'''
检查密码强度
:param password: str 密码
:return: str 密码强度
'''
# 判断密码长度
if len(password) <= 8:
# 判断是否是纯小写或大写英文
if re.match('^[a-z]+$', password) or re.match('^[A-Z]+$', password):
return '弱'
# 判断是否是有小写、大写英文和非英文字符
elif re.match('^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z]).*$', password):
return '中'
elif len(password) <= 16:
# 判断是否是纯小写或大写英文
if re.match('^[a-z]+$', password) or re.match('^[A-Z]+$', password):
return '中'
# 判断是否是有小写英文、大写英文、非英文字符中的两种
elif re.match('^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z]).{2,}$', password):
return '中'
else:
# 判断是否是有小写英文、大写英文、非英文字符中的两种或三种
if re.match('^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z]).{2,}$', password):
if re.match('^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z]).{3,}$', password):
return '强'
else:
return '中'
# 判断是否是有小写英文、大写英文、非英文字符中的两种
elif re.match('^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z]).{2,}$', password):
return '中'
# 默认返回弱
return '弱'
# 测试
print(check_password_strength('123456')) # 弱
print(check_password_strength('abcABC123')) # 中
print(check_password_strength('abcdefg')) # 弱
print(check_password_strength('abcde123')) # 中
print(check_password_strength('Abc123456')) # 中
print(check_password_strength('Abc123456!')) # 强
print(check_password_strength('AbcdefghiJklmn12345')) # 强
运行截图

注意: 本文提供的代码仅供参考,实际应用中可能需要根据具体需求进行调整。
原文地址: https://www.cveoy.top/t/topic/omT8 著作权归作者所有。请勿转载和采集!