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

问题描述

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

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,"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,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,logins_path))
else:
    print("Please enter 1 or 2")

解决方法

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

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

<md5 HASH object @ 0x7f8274221990>

...这不是很有用。

如果您想要散列的实际文本,请调用.hexdigest()

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