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



我有一个登录程序,它对字符串进行哈希处理,并将其存储在一个文件中以创建一个新帐户。当我需要登录时,登录详细信息字符串会被散列,程序会检查散列后的字符串在文件中是否匹配。该程序在没有哈希的情况下工作,但当我对相同的登录详细信息进行哈希时,哈希值就不一样了。我检查过了,字符串完全相同。这是我的代码:

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 ScriptsLogin Programlogins.txt"
signin_message = input("Would you like to: n1. Create an account nor n2. Log inn")
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"))

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

<md5 HASH object @ 0x7f8274221990>

这并不是很有用。

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

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

相关内容

最新更新