使用Python/Bcrypt在MongoDB的用户集合中将密码保存为盐哈希值。

7
我希望生成一个加盐密码哈希,并将其存储在名为“users”的MongoDB集合中,就像这样:

users_doc = { 
    "username": "James",
    "password": "<salted_hash_password>"
}

我不确定如何使用Bcrypt生成哈希密码,然后当我在我的Flask应用程序中登录时,能够检查哈希是否与存储在MongoDB中的哈希密码匹配。

3个回答

9

我不知道你如何使用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)
}

如果您想检查密码,可以使用check_password_hash()函数:

bcrypt.check_password_hash(users_doc["password"], request.form["password"]) # Just an example of how you could use it.

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - c74ckds
你是指盐值代码吗?这个包装函数会自动处理。 - Leandro Poblet
是的,我之前要求盐,但现在我知道那个包装器了。谢谢,它完美地解决了我的问题! - c74ckds

3

使用bcrypt生成盐并将其保存在设置文件中:

import bcrypt
salt = bcrypt.gensalt()

加密密码的方法:

password = "userpassword"
hashed = bcrypt.hashpw(password, bcrypt.gensalt())

检查生成的盐值:

>>> print hashed
$2a$12$C.zbaAxJPVVPKuS.ZvNQiOTVSdOf18kMP4qDKDnM3AGrNyGO5/tTy

要检查一个特定的密码是否与你生成的密码匹配(只需使用盐的散列值创建密码散列并将其与数据库中的密码散列进行比较):
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

0
你可以使用以下方法对密码进行哈希。
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")
                }
            })
        })
    })

在登录时使用以下内容来比较密码。

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);
        })
    })
}))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接