Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save password as salted hash in mongodb in users collection using python/bcrypt

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.

like image 200
c74ckds Avatar asked Jan 14 '15 12:01

c74ckds


2 Answers

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.
like image 186
Leandro Poblet Avatar answered Sep 23 '22 20:09

Leandro Poblet


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
like image 20
avenet Avatar answered Sep 24 '22 20:09

avenet