14 hashlib 案例2 用户注册

问题:无法反向解密时,我们 知道密码明文吗

  • 用户注册
import hashlib
# 1、用户注册
user = input("请输入用户名:").strip()
pwd = input("请输入密码:").strip()

# 2、加密
obj = hashlib.md5('testaa'.encode('utf-8'))
obj.update(pwd.encode('utf-8'))
encrypt_pwd = obj.hexdigest()

# 3、写入文件
with open('userinfo', mode='a', encoding='utf-8') as f:
    f.write(f"{user},{encrypt_pwd}")
  • 用户登录-函数版本
  • 建议结构
  • 全局变量一定要大写,局部变量是小写
  • not,取反

import hashlib

SALT = 'testaa'


def user_input():
    user = input("请输入用户名:").strip()
    pwd = input("请输入密码:").strip()
    return user, pwd


def md5(data_string):
    obj = hashlib.md5(SALT.encode('utf-8'))
    obj.update(data_string.encode('utf-8'))
    return obj.hexdigest()


def user_islogin(user, encrypt_pwd):
    is_success = False
    with open('userinfo', mode='r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            
            # 如果是空的,就让他继续
            if not line:  
                continue
            old_user, old_pwd = line.split(",")
            if old_user == user and old_pwd == encrypt_pwd:
                is_success = True
                break
    return is_success


def get_user_info():
    user_dict = {}
    with open('userinfo', mode='r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            
            # 如果是空的,就让他继续
            if not line:  
                continue
            old_user, old_pwd = line.split(",")
            user_dict[old_user] = old_pwd
    return user_dict


def run():
    # 1、用户注册
    # user, pwd = user_input()

    # 2、密码加密
    # encrypt_pwd = md5(pwd)

    # 3、写入文件
    # with open('userinfo', mode='a', encoding='utf-8') as f:
    #     f.write(f"{user},{encrypt_pwd}")

    #     1、用户登录

    user, pwd = user_input()
    # 2、密码加密
    encrypt_pwd = md5(pwd)

    # 3、读取文件 + 进行密文的比较(简单)登录时,比较方法1
    is_success = user_islogin(user, encrypt_pwd)
    if is_success:
        print('登录成功')
    else:
        print('登录失败')

    # 比较方法2:
    user_dict = get_user_info()
    db_pwd = user_dict.get(user)
    if db_pwd == encrypt_pwd:
        print('登录成功')
    else:
        print('登录失败')


if __name__ == '__main__':
    run()

posted @ 2024-09-28 08:51  jhchena  阅读(5)  评论(0编辑  收藏  举报