加密里面的salt,带加密的nodejs中的SALT和HASH密码

I am trying to figure out how to salt and hash a password in nodejs using the crypto module. I am able to create the hashed password doing this:

UserSchema.pre('save', function(next) {

var user = this;

var salt = crypto.randomBytes(128).toString('base64');

crypto.pbkdf2(user.password, salt, 10000, 512, function(err, derivedKey) {

user.password = derivedKey;

next();

});

});

However I am confused about how to later validate the password.

UserSchema.methods.validPassword = function(password) {

// need to salt and hash this password I think to compare

// how to I get the salt?

}

解决方案

In whatever persistence mechanism (database) you're using, you would store the resulting hash alongside the salt and number of iterations, both of which would be plaintext. If each password uses different salt (which you should do), you must also save that information.

You would then compare the new plain text password, hash that using the same salt (and iterations), then compare the byte sequence with the stored one.

To generate the password (pseudo)

function hashPassword(password) {

var salt = crypto.randomBytes(128).toString('base64');

var iterations = 10000;

var hash = pbkdf2(password, salt, iterations);

return {

salt: salt,

hash: hash,

iterations: iterations

};

}

To validate password (pseudo)

function isPasswordCorrect(savedHash, savedSalt, savedIterations, passwordAttempt) {

return savedHash == pbkdf2(passwordAttempt, savedSalt, savedIterations);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值