如何使用加密检查字符串是否已在 Node.js 中进行哈希处理

How to check if a string is already hashed in Node.js using crypto

本文关键字:js 处理 哈希 Node 加密 何使用 检查 字符串 是否      更新时间:2023-09-26

我正在开发一个应用程序,允许用户更改密码。

我正在使用 Node.js 与 mongoosecrypto .

为了为密码生成哈希,我已经挂接到了模型的pre('save')事件。所以基本上当你使用它时:

var user = new User({password: '123'});
user.save(); // the password will be encrypted automatically

由于能够更改密码,如果用户实际更改了密码或修改了任何其他字段,我需要找到一种方法。例:

var user = User.findById('1234567', function(error, user){
     user.name = 'Hello';
     user.save(); // this will hash the password again, although it is not necessary
})

我正在使用 Node.js 的名为 crypto 的模块为密码生成哈希:

crypto.pbkdf2(password, salt, 5000, 512, 'sha512', function(error, buffer){
        this.mixins.callback.call(callback, [error, buffer.toString('base64')]);
}.bind(this));

有没有办法检查password是否已经是散列的?
如果没有,我将再次生成哈希。

谢谢

这本质上是糟糕的方法。只需调用字段password_hash并始终显式传递哈希。否则,您可能会在一些小的配置更改后意外开始存储未散列的密码。

此外,如果允许任意字符串作为密码,则通常无法区分哈希和未哈希字符串。

哈希字符串具有哈希算法标识符前缀。可以通过检查字符串是以 $2a$ 开头还是以 $2b$ 开头来验证

参考