简体   繁体   English

使用python / bcrypt将密码保存为用户集合中mongodb中的salted哈希

[英]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: 我想生成一个salted密码哈希并将其存储在名为users的MongoDB集合中,如下所示:

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. 我不确定如何使用Bcrypt生成散列密码,然后当我登录我的烧瓶应用程序时,能够检查散列是否与存储在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: 我不知道你是如何使用mongodb来传输数据的,但是如果你想对传递进行散列,那么就像以下一样简单:

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: 然后,如果要检查密码,可以使用check_password_hash()函数:

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: 使用bcrypt生成salt并将其保存在设置文件中:

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): 要检查给定的密码是否与您生成的密码匹配(只需使用salt创建密码的哈希值并将其与数据库上的密码进行比较):

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

You can use the following the hash your password. 您可以使用以下哈希密码。

app.post("/register", function(req, res){
    var type = req.body.type
    var newUser = new Student({
        username: req.body.username,
        gender: req.body.gender,
        rollnumber: req.body.rollnumber,
        dob: req.body.dob,
        email: req.body.email,
        type: req.body.type,
        password: req.body.password
    })

    req.checkBody('username','UserName is Required').notEmpty();
    req.checkBody('rollnumber','Roll Number is Required').notEmpty();
    req.checkBody('email','Email Required').notEmpty();
    req.checkBody('email','Email Invalid').isEmail();
    req.checkBody('password','Password is Required').notEmpty();
    req.checkBody('password1','Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();
    if(errors){
        res.render('Sregister', {errors: errors});
    }else{
    bcrypt.genSalt(10, function(err,  salt){
        bcrypt.hash(newUser.password, salt, function(err, hash){
            if(!err){
                newUser.password = hash;
            }
            newUser.save(function(err){
                if(!err){
                    console.log("success in reg");
                    res.redirect("/student/login")
                }
            })
        })
    })

And use the following to compare the password while logging in. 并在登录时使用以下内容来比较密码。

passport.use('student', new LocalStrategy(function(username, password, done){
    var query = {username: username};
    Student.findOne(query, function(err, student){
        if(err) throw err;
        if(!student){
            return done(null, false);
        }
        bcrypt.compare(password,student.password, function(err, isMatch){
            if(err) throw err;
            if(isMatch)
                return done(null, student);
            else
                return done(null,false);
        })
    })
}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM