Python 在 .txt 文件中以不同方式保存密码 [关闭]

问题描述 投票:0回答:0

我在 PyCharm 中创建了一个基本的 python 登录系统。所有功能都有效。所有用户名和密码都保存到一个 .txt 文件中。当我创建新的用户名和密码时,PyCharm 和 .txt 文件中的密码不同。例如,我在 PyCharm 中创建了用户名 robotman,密码 7777Spy007。在 .txt 文件中,用户名为 robotman,密码为 874775653b3c315b236d8b9fd21a1a330eb613c78c7b80ddb7c96f36a7b35452。请参考screenshot.

我可以在 PyCharm 中使用用户名 robotman 和密码 7777Spy007 登录。请参阅attached.

然而,当我在 PyCharm 中“查看帐户”时,它反映了 .txt 文件。请参阅attached.

我需要在 PyCharm 中“查看帐户”来显示“robotman 7777Spy007”我应该怎么做才能解决这个问题?

代码:

# Import all needed modules or libraries for program

import getpass
import hashlib
from datetime import date
import time
import string
import random

# Define functions

def register():
    print("")
    print("-" * 70)
    print("Register")
    print("-" * 70)
    print("")
    register_password_creation = input("Please choose an option: \n\nS - Choose password\nR - Generate random password\nM - Main menu\n").lower()
    print("")
    if register_password_creation == "s":
        register_self_password()
    elif register_password_creation == "r":
        register_auto_generator_password()
    elif register_password_creation == "m":
        register()
    else:
        print("-" * 70)
        print("Please enter a valid character")
        print("-" * 70)
        register()
    print("")

def add_user_info(user_info: list):
    with open("accounts.txt", "a") as file:
        for info in user_info:
            file.write(info)
            file.write(" ")
        file.write("\n")

def user_already_exist(username, user_password=None):
    if user_password == None:
        with open("accounts.txt ", "r") as file:
            for line in file:
                line = line.split()
                if line[0] == username:
                    return True
        return False
    else:
        user_password = hash_password(user_password)
        users_info = {}
        with open("accounts.txt ", "r") as file:
            for line in file:
                line = line.split()
                if line[0] == username and line[1] == user_password:
                    users_info.update({line[0]: line[1]})
        if users_info == {}:
            return False
        return users_info[username] == user_password


def display_user_already_exist_message():
    while True:
        print()
        error = input("Username already exists\n\nT - Try again:\nL - Login:\nM - Main Menu\n").lower()
        if error == "t":
            register()
            break
        elif error == "l":
            login()
            break
        elif error == "m":
            main()
            break


def register_self_password():
    print("-" * 70)
    print("Choose password")
    print("-" * 70)
    print()
    while True:
        username = input("Enter username" + " " * 20 + "| \n")
        if username != "":
            break
    username = sanitizename(username)
    if user_already_exist(username):
        display_user_already_exist_message()
    else:
        while True:
            user_password = input("Enter password" + " " * 16 + "| \n")
            if user_password != '':
                break
        while True:
            confirm_password = input("Confirm password" + " " * 14 + "| \n")
            if confirm_password == user_password:
                break
            else:
                print("Passwords don't match")
                register_self_password()
        if user_already_exist(username, user_password):
            while True:
                print()
                error = input(
                    "You are already registered\n\nT - Try again\nL - Login\nE - Main Menu\n").lower()
                if error == "t":
                    register()
                    break
                elif error == "l":
                    login()
                    break
                elif error == "e":
                    main()
                    break
        add_user_info([username, hash_password(user_password)])
        print()
        print("Registration Successful ")
        login()


def register_auto_generator_password():
    print("-" * 70)
    print("Random password generator")
    print("-" * 70)
    print()
    while True:
        username = input("Enter username" + " " * 20 + "| \n")
        if username != "":
            break
    username = sanitizename(username)
    if user_already_exist(username):
        display_user_already_exist_message()
    else:
        print("Username is available")
        while True:
            def gen(length_lower_case):
                lower_case = string.ascii_lowercase
                generate = "".join(random.choice(lower_case) for i in range(length_lower_case))
                return generate

            lower_case_characters = int(input("How many lower case characters do you want?\n"))
            lcc = (gen(lower_case_characters))

            # print(lcc)

            def gen(length_upper_case):
                upper_case = string.ascii_uppercase
                generate = "".join(random.choice(upper_case) for i in range(length_upper_case))
                return generate

            upper_case_characters = int(input("How many upper case characters do you want?\n"))
            ucc = (gen(upper_case_characters))

            # print(ucc)

            def gen(length_numbers):
                numbers = string.digits
                generate = "".join(random.choice(numbers) for i in range(length_numbers))
                return generate

            number_characters = int(input("How many numbers characters do you want?\n"))
            nuc = (gen(number_characters))

            # print(nuc)

            def gen(length_symbols):
                symbols = string.punctuation
                generate = "".join(random.choice(symbols) for i in range(length_symbols))
                return generate

            symbol_characters = int(input("How many symbols characters do you want?\n"))
            syc = (gen(symbol_characters))
            # print(syc)

            generator = lcc + ucc + nuc + syc
            length = lower_case_characters + upper_case_characters + number_characters + symbol_characters
            temp = random.sample(generator, length)
            # print(temp)
            random_password = "".join(temp)
            print("Password chosen is " + " " * 20 + "| \n" + random_password)

            add_user_info([username, hash_password(random_password)])
            print("")
            print("User account " + username + " is now registered")
            print("Please Login")
            print("")
            login()
            break

def login():
    print("")
    print("-" * 70)
    print("Login")
    print("-" * 70)
    print()
    users_info = {}
    with open('accounts.txt', 'r') as file:
        for line in file:
            line = line.split()
            users_info.update({line[0]: line[1]})
    while True:
        username = input("Enter username" + " " * 20 + "| \n")
        username = sanitizename(username)
        if username not in users_info:
            print("Username " + username + " is not registered\nPlease register")
            register()
            print()
        else:
            user_password = getpass.getpass = input("Enter password" + " " * 16 + "| \n")
            if check_password_hash(user_password, users_info[username]):
                print("-" * 70)
                print("Login Successful")

            else:
                print("Incorrect password\nPlease try again\n")
                login()
        break

def sanitizename(username):
    username = username.split()
    username = "-".join(username)
    return username

def hash_password(password):
    return hashlib.sha256(str.encode(password)).hexdigest()

def check_password_hash(password, hash):
    return hash_password(password) == hash

def admin_access_display():
    print("-" * 70)
    print("Display database for admin only")
    print("Username & passwords")
    print("")
    f = open("accounts.txt ", "r")
    database_contents = f.read()
    print(database_contents)
    print("-" * 70)
    print("End")
    print("-" * 70)

def intro():
    print("-" * 70)
    today = date.today()
    today_date = today.strftime("%B %d, %Y")
    print("Today's date is ", today_date)
    print("-" * 70)
    print("Python Login System")
    main()

def main():
    print("-" * 70)
    print("Main Menu")
    print("-" * 70)
    print("What would you like to do?")
    option = input("A: Login, B: Register, C: View Accounts, D: Exit  | \n")
    if option == "A" or option == "a":
        login()
    elif option == "B" or option == "b":
        register()
    elif option == "C" or option == "c":
        admin_access_display()
    elif option == "D" or option == "d":
        time.sleep(3); exit()
    else:
        print("A valid choice has not been entered")
        print("Please try again")
        main()


# Start of the program
intro()
python pycharm
© www.soinside.com 2019 - 2024. All rights reserved.