散列的相同字符串在散列两次时不相同

Hashed identical strings aren't the same when hashed twice

我有一个登录程序,可以对字符串进行哈希处理并将其存储在文件中以创建新帐户。当我需要登录时,登录详细信息字符串被散列,程序检查散列字符串是否在文件中匹配。该程序无需散列即可运行,但当我对相同的登录详细信息进行散列时,散列值并不相同。我已经检查过,字符串完全相同。这是我的代码:

import tkinter
import math
import os
import hashlib

# The login function #
def login(username, password, file_path):
    file_new = open(file_path, "a")
    file_new.close()

    file = open(file_path, "r")
    file_content = file.read()
    print(file_content)
    file.close()

    hashed_username = hashlib.md5(bytes(username, "utf-8"))
    hashed_password = hashlib.md5(bytes(password, "utf-8"))
    print(f"Hashed username: {hashed_username}, hashed password: {hashed_password}")

    if f"{hashed_username},{hashed_password}" in file_content[:]:
        return "You were logged in successfully"
    else:
        return "We could not find your account. Please check your spelling and try again."

# The account creation function #
def newaccount(username, password, file_path):
    file_new = open(file_path, "a")
    file_new.close()

    # Reading the file #
    file = open(file_path, "r")
    file_content = file.read()
    print(file_content)
    file.close()

    # Hashing the account details #
    hashed_username = hashlib.md5(bytes(username, "utf-8"))
    hashed_password = hashlib.md5(bytes(password, "utf-8"))
    print(f"Hashed username: {hashed_username}, hashed password: {hashed_password}")
    
    file_append = open(file_path, "a")

    # Checking to see if the details exist in the file #
    if f"{hashed_username},{hashed_password}" in file_content[:]:
        file_append.close()
        return "You already have an account, and were logged in successfully"
    else:
        # Writing the hashed details to the file #
        file_append.write(f"{hashed_username},{hashed_password}\n")
        file_append.close()
        return "New account created."        

logins_path = "Random Scripts\Login Program\logins.txt"

signin_message = input("Would you like to: \n1. Create an account \nor \n2. Log in\n")
if signin_message == "1":
    print("User chose to create account")
    newacc_username = input("Input a username: ")
    newacc_password = input("Input a password: ")
    print(newaccount(newacc_username, newacc_password, logins_path))
elif signin_message == "2":
    print("User chose to log in")
    username = input("Input your username: ")
    password = input("Input your password: ")
    print(login(username, password,logins_path))
else:
    print("Please enter 1 or 2")

hashed_username = hashlib.md5(bytes(username, "utf-8"))

这个函数 returns 一个散列对象,当你打印它或将它写入文件时,你会得到这样的东西:

<md5 HASH object @ 0x7f8274221990>

...这不是很有用。

如果您想要哈希的实际 text,请调用 .hexdigest():

hashed_username = hashlib.md5(bytes(username, "utf-8")).hexdigest()
# returns e.g. "47bce5c74f589f4867dbd57e9ca9f808"