Checking passwords
The following example checks a password against a hashed value.
Example 1:
Here we will check whether the user has entered the correct password or not, for that we can use bcrypt.checkpw(password, hash). At first, let’s assume the user entered the wrong password.
Python3
import bcrypt # example password password = 'passwordabc' # converting password to array of bytes bytes = password.encode( 'utf-8' ) # generating the salt salt = bcrypt.gensalt() # Hashing the password hash = bcrypt.hashpw(bytes, salt) # Taking user entered password userPassword = 'password000' # encoding user password userBytes = userPassword.encode( 'utf-8' ) # checking password result = bcrypt.checkpw(userBytes, hash ) print (result) |
Output:
Example 2:
Now let’s see what happens when passwords are matched:
Python3
import bcrypt # example password password = 'passwordabc' # converting password to array of bytes bytes = password.encode( 'utf-8' ) # generating the salt salt = bcrypt.gensalt() # Hashing the password hash = bcrypt.hashpw(bytes, salt) # Taking user entered password userPassword = 'passwordabc' # encoding user password userBytes = userPassword.encode( 'utf-8' ) # checking password result = bcrypt.checkpw(userBytes, hash ) print (result) |
Output:
Hashing Passwords in Python with BCrypt
In this article, we will see how to hash passwords in Python with BCrypt. Storing passwords in plain text is a bad practice as it is vulnerable to various hacking attempts. That’s why it is recommended to keep them in a hashed form.