Получение пароля для совпадения с его ha sh в функции входа в систему с использованием Python, SQlite и bcrypt - PullRequest
0 голосов
/ 22 апреля 2020

РЕДАКТИРОВАТЬ: я переписал код, частично на основе предложений ниже, а частично с помощью других решений, использующих bcrypt, и до сих пор не повезло.

Я пишу функцию входа в систему для программы 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: ")  # prompts the user to enter their password
        with sqlite3.connect("C:\sqlite\db\SUTHATusers.db") as db:
            # connects to the database 'SUTHATusers.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")
        stored_hash_encoded = stored_hash.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(password_encoded, salt)  # hashes the password that has been encoded

        if bcrypt.checkpw(password_encoded, stored_hash_encoded) == stored_hash_encoded:
            # 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 пароль в базе данных.

Я, наверное, правильно сделал sh (!) Этой функции входа в систему - может кто-нибудь помочь мне установить правильный путь? Я полностью сбит с толку. Заранее спасибо.

1 Ответ

1 голос
/ 22 апреля 2020

bcrypt.checkpw возвращает логическое значение, поэтому ваш код сравнивает это логическое значение с хэшированным, что будет ложным

if bcrypt.checkpw(password_hash, hashed) == hashed:

Удалите сравнение, подобное этому

if bcrypt.checkpw(password_hash, hashed):

Вот пример из документации:

>>> if bcrypt.checkpw(password, hashed):
...     print("It Matches!")
... else:
...     print("It Does not Match :(")
...