14 hashlib 案例2 使用者註冊

jhchena發表於2024-09-28

問題:無法反向解密時,我們 知道密碼明文嗎

  • 使用者註冊
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()

相關文章