Node.js中与PHP hash函数相当的函数是什么(包括salt和原始输出)?

3
我的同事有一个存储账户信息的数据库;账户的SHA256哈希密码和盐值以二进制数据(blob)的形式存储在列中。
使用以下PHP代码(true表示原始输出)对密码进行哈希:
hash("sha256", $salt . $password, true);

我正在尝试在Node.js服务器上实现身份验证,必须从PHP获取与数据库中存储的相同的哈希密码,但似乎无法正常工作。
/**
 * Validates a password sent by an end user by comparing it to the 
 * hashed password stored in the database. Uses the Node.js crypto library.
 *
 * @param password The password sent by the end user.
 * @param dbPassword The hashed password stored in the database.
 * @param dbSalt The encryption salt stored in the database.
 */
function validatePassword(password, dbPassword, dbSalt) {
    // Should the dbSalt be a Buffer, hex, base64, or what?
    var hmac = crypto.createHmac("SHA256", dbSalt);
    var hashed = hmac.update(password).digest('base64');
    console.log("Hashed user password: " + hashed);
    console.log("Database password: " + dbPassword.toString('base64'));
    return hashed === dbPassword;
}
2个回答

5

经过大量实验,我找到了一个解决方案。

/**
 * Encrypts a password using sha256 and a salt value.
 *
 * @param password The password to hash.
 * @param salt The salt value to hash with.
 */
function SHA256Encrypt(password, salt) {
    var saltedpassword = salt + password;
    var sha256 = crypto.createHash('sha256');
    sha256.update(saltedpassword);
    return sha256.digest('base64');
}

/**
 * Validates a password sent by an end user by comparing it to the
 * hashed password stored in the database.
 *
 * @param password The password sent by the end user.
 * @param dbPassword The hashed password stored in the database, encoded in Base64.
 * @param dbSalt The encryption salt stored in the database. This should be a raw blob.
 */
function validatePassword(password, dbPassword, dbSalt) {
    var hashed = SHA256Encrypt(password, dbSalt.toString('binary'));
    return hashed === dbPassword;
}

感谢TravisO,他给了我正确的方向。

2
不要使用SHA哈希来存储密码。您应该使用专门为密码设计的东西,如bcrypt。每秒可以破解数十亿个SHA256编码的密码。加盐有所帮助,但比您想象的要少得多。如果您正在与现有的PHP应用程序进行交互,那么您可能会陷入困境,但即使是PHP也支持bcrypt。 - tadman
这不是我的选择,而且现在改变它为时已晚。PHP代码已经由其他人编写,而且非常庞大。 - afollestad

2

谢谢你的帮助,虽然这并没有完全解决我的问题,但它让我找到了正确的方向,我已经在下面发布了一个解决方案。 - afollestad

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