带加密的nodejs中的SALT和HASH密码 [英] SALT and HASH password in nodejs w/ crypto

查看:269
本文介绍了带加密的nodejs中的SALT和HASH密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何使用crypto模块对nodejs中的密码进行加盐和哈希处理.我可以执行以下操作来创建哈希密码:

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.

生成密码(伪)

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

验证密码(伪)

function isPasswordCorrect(savedHash, savedSalt, savedIterations, passwordAttempt) {
    return savedHash == pbkdf2(passwordAttempt, savedSalt, savedIterations);
}

这篇关于带加密的nodejs中的SALT和HASH密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆