10.0 Django 密码验证与加密

密码验证与MD5加密模块

密码验证

前端\django\myweb\blog\utils\password.py

import string
import re

def check_fips_password_complexity(password):

    # 验证密码长度
    if len(password) < 8:
        return "密码长度不合格,不低于8位"

    # 定义字符集
    uppercase_letters = string.ascii_uppercase
    lowercase_letters = string.ascii_lowercase
    digits = string.digits
    special_chars = string.punctuation.replace("?", "")  # 假设 ? 是不允许的特殊字符

    # 检查各个字符集是否至少出现一次
    if not any(char in uppercase_letters for char in password):
        return "密码必须包含至少一个大写字母"
    if not any(char in lowercase_letters for char in password):
        return "密码必须包含至少一个小写字母"
    if not any(char in digits for char in password):
        return "密码必须包含至少一个数字"
    if not any(char in special_chars for char in password):
        return "密码必须包含至少一个特殊字符"

    # 检查密码是否包含不允许的字符
    if re.search(r'[\s\x00]', password):
        return "密码包含不允许的字符(空格、中止字符等)"

    # print("密码符合FIPS复杂度要求")
    return True

# 使用示例
if __name__ == "__main__":
    password = "Example1="
    str = check_fips_password_complexity(password)
    print(str)

MD5加密

前端\django\myweb\blog\utils\encrypt.py

from django.conf import settings
import hashlib
import os
import sys

sys.path.append(r"D:\git-python\前端\django\myweb")
os.environ["DJANGO_SETTINGS_MODULE"] = "myweb.settings"

def md5(pwd):
    # salt = "xxxxxxxx"
    # obj = hashlib.md5()
    # obj = hashlib.md5(salt.encode('utf-8'))   # 加盐
    # SECRET_KEY = getattr(settings, "SECRET_KEY", None)
    obj = hashlib.md5(settings.SECRET_KEY.encode('utf-8'))   # 使用Django默认生成的随机SECRET_KEY
    obj.update(pwd.encode('utf-8'))
    return obj.hexdigest()

if __name__ == "__main__":
    password = "Example1="
    str = md5(password)
    print(str)

使用案例

前端\django\myweb\blog\utils\form.py

from blog.models import *
from blog.utils.modelform import BootStrapModelForm
from django.core.exceptions import ValidationError
from django import forms
from blog.utils.password import check_fips_password_complexity
from blog.utils.encrypt import md5

# 新增管理员 modelform
class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码", widget=forms.PasswordInput(render_value=True))
        # PasswordInput(render_value=True) 验证不能过密码不会重置为空

    class Meta:
        model = Admin
        fields = ["username", "password", "confirm_password"]
        # fields = "__all__"    # 所有字段
        # exclude = ['level']   # 排除字段

        widgets = {
            "password": forms.PasswordInput(attrs={"placeholder": "密码:大小写字符|数字|特殊字符|8位以上"}, render_value=True),
        }

    # 密码复杂度验证与MD5加密
    def clean_password(self):
        # from blog.utils.password import check_fips_password_complexity
        # from blog.utils.encrypt import md5

        pwd = self.cleaned_data.get("password")

        if check_fips_password_complexity(pwd) == True:
            return md5(pwd)
        else:
            str = check_fips_password_complexity(pwd)
            raise ValidationError(str)

    # 数据验证 方式二 钩子方法
    def clean_confirm_password(self):
        # from blog.utils.encrypt import md5

        # print(self.cleaned_data)
        pwd = self.cleaned_data.get("password")   # 已md5加密
        confirm = md5(self.cleaned_data.get("confirm_password"))

        # 检查两次输入的密码是否一致

        if confirm != pwd:
            raise ValidationError("两次输入的密码不一致")

        # 验证完成后return该字段数据会保存至数据库,所以需要return原数据
        return confirm  # 验证通过