I want to generate a salted password hash and store it in MongoDB collection called users, like this:
users_doc = {
"username": "James",
"password": "<salted_hash_password>"
}
I'm not sure how to generate the hashed password using Bcrypt, then when I login in my flask app, be able to check if the hash matches with the hashed password stored in MongoDB.
I don't know how you use mongodb to bring the data, but if you want to hash the pass it's as easy as:
from flask import Flask
from flask.ext.bcrypt import Bcrypt
app = Flask(__name__)
bcrypt = Bcrypt(app)
# Your code here...
users_doc = {
"username": "james",
"password": bcrypt.generate_password_hash(password)
}
And then if you want to check the password, you can use the check_password_hash()
function:
bcrypt.check_password_hash(users_doc["password"], request.form["password"]) # Just an example of how you could use it.
Generate a salt using bcrypt and keep it saved in your settings file:
import bcrypt
salt = bcrypt.gensalt()
To encrypt the password:
password = "userpassword"
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
Checking the generated salt:
>>> print hashed
$2a$12$C.zbaAxJPVVPKuS.ZvNQiOTVSdOf18kMP4qDKDnM3AGrNyGO5/tTy
To check if a given password matches the one you generated (just create a hash of the password using the salt and compare it to the one on the database):
given_password = "password"
hashed_password = bcrypt.hashpw(password, salt) #Using the same salt used to hash passwords on your settings
hashed_password == hashed #In this case it returns false, because passwords are not the same
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With