python内置函数hashlib密码加密处理

记录一下

python内置函数hashlib密码加密处理

import hashlib
#密码加密
def get_md5(password) : # password只能传入字符串
    m = hashlib.md5()
    m.update(password.encode('utf-8'))
    return m.hexdigest()

def register(username,password) :
    #写入注册密文至文件中
    md5_pwd = get_md5(password)
    with open('uesr_pwd.txt',mode='at',newline='',encoding='utf-8') as f :
        f.write(f'\n{username}|{md5_pwd}')

def get_user_pwd() :
    user_dict = {}
    with open('uesr_pwd.txt',mode='rt',encoding='utf-8') as f:
        for line in f.readlines()[1:]:
            line = line.replace('\n','')
            line_list = line.strip().split('|')
            user_dict[line_list[0].strip()] = line_list[1].strip()
    return user_dict

def login(username,password) :
    dic = get_user_pwd()
    count = 1
    while count < 4 :
        md5_pwd = get_md5(password)
        if username in dic and dic[username] == md5_pwd :
            print('登陆成功')
            return True
        else:
            username = input('账户名或密码不正确,请重新输入账户名')
            password = input('账户名或密码不正确,请重新输入密码')
        count += 1
    return False
def action():
    while True:
        choice = input('1.注册 2.登陆 3.退出 请选择:')
        if choice in ['1','2','3']:
            choice = int(choice)
            if choice == 1 :
                username = input('请输入用户名:').strip()
                password = input('请输入密码:').strip()
                register(username,password)
            elif choice == 2 :
                username = input('请输入用户名:').strip()
                password = input('请输入密码:').strip()
                login(username,password)
            elif choice == 3 :
                break
            else:
                print('您的输入有误,请重新输入!')
        else:
            print('您的输入有误,请重新输入!')
action()

版权声明:本文为weixin_40981660原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。