You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

密码强度检测代码异常求助:含特殊字符即判定为强密码

密码强度检测程序问题排查与修复

问题概述

编写密码强度检测程序时,预设规则为:密码包含特殊字符、大写字母、小写字母、数字4种特征中3种及以上则为强密码,仅含2种则为中等密码。但当前代码存在以下异常:

  • 只要密码含特殊字符,无论其他组合如何都判定为强密码;
  • 部分不含特殊字符的密码(如123456789NOSYM、NOSYMBOLSPLEAS、123456789YES!!)错误输出Strong,而非预期的Medium。

错误原因分析

  1. 字符逻辑判断完全错误:代码中使用any(i.isupper and i.islower and i.isdigit and i in specialCharacters for i in password),单个字符不可能同时满足大写、小写、数字、特殊字符四种属性,此条件永远为False,导致后续分支直接触发。
  2. 分支逻辑偏离规则:length ==14分支中,any(not i.isupper for i in password)这类判断完全错误——只要密码存在一个非大写字符,就直接判定为Strong,完全没有统计特征种类数量,违背了“按特征种类数判定强度”的核心规则。
  3. 未统计特征种类:代码没有统计密码实际包含的特征数量,而是用零散的any判断,导致逻辑混乱。
  4. 拼写错误:Meduim应为Medium。

修复方案

核心思路是先统计密码包含的特征种类数,再结合密码长度判定强度:

修复后的完整代码

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def getInfo():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def passwordStrength():
    password = ''
    strength = ''
    length = 0
    specialCharacters = "!@#$%^&*()`~-_=+[{]}\|;:'<,>.?/"
    
    # 修正POST请求的判断逻辑,确保Password字段存在
    if request.method == 'POST' and 'Password' in request.form:
        password = str(request.form.get('Password'))
        length = len(password)
        
        # 统计密码包含的特征种类
        has_upper = any(c.isupper() for c in password)
        has_lower = any(c.islower() for c in password)
        has_digit = any(c.isdigit() for c in password)
        has_special = any(c in specialCharacters for c in password)
        feature_count = sum([has_upper, has_lower, has_digit, has_special])
        
        # 根据长度和特征数判定强度
        if length >= 18:
            strength = 'Godlike'
        elif length == 17:
            if feature_count >= 4:
                strength = 'Godlike'
            elif feature_count >= 3:
                strength = 'Strong'
            elif feature_count == 2:
                strength = 'Medium'
            else:
                strength = 'Weak'
        elif length == 14:
            if feature_count >= 3:
                strength = 'Strong'
            elif feature_count == 2:
                strength = 'Medium'
            else:
                strength = 'Weak'
        else:
            # 处理其他长度的密码
            if feature_count >= 3:
                strength = 'Strong'
            elif feature_count == 2:
                strength = 'Medium'
            else:
                strength = 'Weak'
    
    # 返回结果到模板,可根据实际需求调整返回方式
    return render_template('index.html', strength=strength)

关键修复点说明

  • 特征统计:通过any()分别判断四种特征是否存在,用sum()统计特征数量(布尔值在sum中会被转为1/0)。
  • 逻辑修正:严格按照“特征数≥3为强、=2为中等”的规则,结合长度判断Godlike等级。
  • 请求校验:修正POST请求的判断条件,确保Password字段存在后再处理。
  • 拼写修正:将Meduim改为Medium。

内容的提问来源于stack exchange,提问作者Jack Pendergast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:37:40