我应该如何在MongoDB中存储盐和密码
我正试图在MongoDB中存储密码和盐,我不确定应该使用哪种数据types。 当我使用string时,encryption的密码看起来是正确存储的,但是生成的salt是用new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
,似乎有没有被识别的字符。 例如,我有一个盐储存为 y_ 6j( l〜Z)0 \“,我不认为这是正确的。
问题是它存储为一个string?
注册用户时,可以使用brypt生成散列密码。 我们把这个密码称为P#1。 将这个散列密码(P#1)保存在数据库中,而不是salt。
在用户login时,生成用户发送密码的散列版本,我们称之为P#2。 现在你只需要匹配P#1和P#2。 如果它们匹配,则用户通过身份validation。 这样你就可以执行authentication,而不需要在数据库中保存salt。
我会试着用一个简单的方式来帮助一个例子。
//我的用户架构
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bcrypt = require('bcrypt-nodejs'); var userSchema = new Schema({ username: String password: String, }); // hash the password userSchema.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; // checking if password is valid userSchema.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.password); }; var User = mongoose.model('user', userSchema); module.exports = User;
//我的API用于注册和authentication用户
var User = require('/path/to/user/model'); app.post('/register', function(req, res) { var new_user = new User({ username: req.username }); new_user.password = new_user.generateHash(userInfo.password); new_user.save(); }); app.post('/login', function(req, res) { User.findOne({username: req.body.username}, function(err, user) { if (!user.validPassword(req.body.password)) { //password did not match } else { // password matched. proceed forward } }); });
希望它可以帮助你!
- 处理令牌的体系结构(NodeJS)(MongoDB)
- 在子数组上的MongoDB查询
- 将范围传递给db.collection.group
- Mongoose findOne不适用于特定的查询,但为其他人工作
- Nodejs Express MongoClient收集检索
- Node.js摩卡unit testing错误重新:蒙哥马与Mockgoose嘲笑,“错误设置集合:会话TTL索引”
- 如何得到mongoose模型的所有计数?
- Azure Cosmos DB:TypeError:无法读取未定义的属性'electionId'
- 在Angular 2 Firebase App中的net :: ERR_CONNECTION_CLOSED