【发布时间】:2017-03-10 23:19:27
【问题描述】:
我有一组服务器端功能, 1.
- 生成随机盐
- 使用密码和盐来创建哈希
-
调用第二个函数创建返回的散列密码
var sha512 = function(password, salt){ var hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ hash.update(password); var value = hash.digest('hex'); return { salt:salt, passwordHash:value }; }; //--------------Function to hash password function saltHashPassword(userpassword) { var salt = genRandomString(16); /** Gives us salt of length 16 */ var passwordData = sha512(userpassword, salt); console.log('UserPassword = '+userpassword); console.log('Passwordhash = '+passwordData.passwordHash); console.log('\nSalt = '+passwordData.salt); return passwordData; } //---------------------- // Function to generate salt var genRandomString = function(length){ return crypto.randomBytes(Math.ceil(length/2)) .toString('hex') /** convert to hexadecimal format */ .slice(0,length); /** return required number of characters */ };
每当我在注册页面中获得用户名和密码时,我都可以调用 saltHashPassword(passwordinstring) 并获得哈希和盐。然后我将它保存到猫鼬模式中的用户文档中。
当用户尝试登录时如何解密?
这是我目前在用户模式 user.js 中编写的方法。我不知道如何为提供的电子邮件存储盐。
// this authenticates the user against the database
UserSchema.statics.authenticate = function(email, password, callback){
User.findOne({email: email})
.exec(function(error, user){
if(error){
return callback(error);
}else if(!user){
var err = new Error("User not found");
err.status = 401;
return callback(err);
}
// if we reach this part of the code, then there is a valid username
// I could call sha512(password, salt) and get the hash and then
// match the two calculated hashed passwords. But how do
// I query the salt within a mongo query?
// every user has email, hashed_password, salt fields in its document
});
};
【问题讨论】:
标签: node.js mongodb encryption hash