Я пишу функцию входа в систему для программы Python и пытаюсь убедиться, что при вводе пароля он соответствует его ha sh, который хранится в базе данных пользователей. Я пробовал несколько разных версий этого - сначала я использовал hashlib и md5, а затем переключился на bcrypt, когда понял, что это будет более эффективно при хешировании паролей.
В любом случае, я пробовал несколько итераций этого кода и ни один из них, похоже, не работает. Это модуль входа в систему:
def login(): # the module which allows existing users to login
while True:
username = input("Please enter your username: ") # prompts the user to enter their username
password = input("Please enter your password: ") # asks the user to enter their password
with sqlite3.connect("C:\sqlite\db\database.db") as db: # prompts
# connects to the database 'database.db', linking to its file path on the hard drive
cursor = db.cursor() # cursor allows the database to be traversed
cursor.execute("SELECT password FROM users WHERE username = ?", (username,))
# cursor executes the above SQL command
stored_hash = cursor.fetchone() # returns the results of the SQL command
password_encoded = password.encode("utf-8")
# encodes the password input by the user so that bcrypt can understand it
#salt = bcrypt.gensalt() # gets the salt
#hashed = bcrypt.hashpw(stored_hash, salt) # hashes the password that has been encoded
#if bcrypt.checkpw(password_encoded, stored_hash) == stored_hash:
if hmac.compare_digest(password_encoded, stored_hash):
# checks the encoded password entered by the user against its hash
# if they match, the user is logged in
print("Welcome " + username) # prints a welcome message and the username
break # ends the if statement
else: # this is run if no matching username and password has been found in the 'users' table
# if no passwords are found or the password entered is incorrect, this if statement is run
print("Username and password not recognized ")
# message telling the user that their details have not been recognised
again = input("Do you want to try again? y/n: ") # asks the user if they want to re-enter their details
if again == "n": # if the user chooses not to re-enter their details, the program restarts
print("Bye bye") # goodbye message is displayed to the user
time.sleep(1) # program pauses for one second
sys.exit()
Работает функция создания пользователя - она запрашивает имя пользователя, пароль, который необходимо ввести дважды, а затем сохраняет имя пользователя и га sh пароля в база данных.
На этой последней итерации я продолжаю получать сообщение об ошибке «TypeError: требуется объект, похожий на байты, а не« tuple »». Я попробовал то, на что похоже все, и ничего не работает. Я полностью сбит с толку. Заранее спасибо.
РЕДАКТИРОВАТЬ: Traceback:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\plugins\python-ce\helpers\pydev\pydevd.py", line 1434, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/familypc/PycharmProjects/suTHAT/login.py", line 110, in <module>
menu() # runs the 'menu' function
File "C:/Users/familypc/PycharmProjects/suTHAT/login.py", line 96, in menu
login()
File "C:/Users/familypc/PycharmProjects/suTHAT/login.py", line 29, in login
if hmac.compare_digest(password_encoded, stored_hash):
TypeError: a bytes-like object is required, not 'tuple'