📜  Node.js 中的密码验证

📅  最后修改于: 2022-05-13 01:56:41.351000             🧑  作者: Mango

Node.js 中的密码验证

在用于密码哈希和验证的 Node 中,我们可以使用称为 bcryptjs npm-bcryptjs 的 npm 库。

bcryptjs 的安装: Node.js 包含一个内置的加密模块的 randomBytes 接口,用于获取安全随机数。

npm install bcryptjs

方法:

  • 要散列密码,请使用bcrypt.hash(plainTextPassword, salt, callback)如果没有传递回调,则返回一个承诺。
  • 要使用散列密码验证纯文本密码,请使用bcrypt.compare(plainTextPassword, hashedPassword, callback)如果没有传递回调,它也会返回一个承诺。

示例 1:

// Use bcryptjs module
const bcrypt = require("bcryptjs");
  
// Store the password into variable
const password = "password123";
  
// Use bcrypt.hash() function to hash the password
bcrypt.hash(password, 8, (err, hashedPassword) => {
    if (err) {
        return err;
    }
      
    // Display the hashed password
    console.log(hashedPassword);
      
    // Use bcrypt.compare() function to compare
    // the password with hashed password
    bcrypt.compare(password, hashedPassword, (err, isMatch) => {
        if( err ) {
            return err;
        }
          
        // If password matches then display true
        console.log(isMatch);
    });
});

输出:

$2a$08$PV4rYpBwXUPAGuMedxUnAOxq/TozK9o/QSUWaKE1XL8psOyZ.JL4q
true

示例 2:

// Use bcryptjs module
const bcrypt = require("bcryptjs");
  
// Store the password into variable
const password = "password123";
  
// Use bcrypt.hash() function to hash the password
bcrypt.hash(password, 8).then(hashedPassword => {
   
    // Display the hashed password
    console.log(hashedPassword);
      
    // Compare the password with hashed password
    // and return its value 
    return bcrypt.compare(password, hashedPassword);
   
}).then(isMatch => {
   
    // If password matches then display true
    console.log(isMatch);
}).catch(err => {
  
    // Display error log
    console.log(err);
});

输出:

$2a$08$LKZU9S9WVs3C.S/zpu2U7eua/ocfzD1ytF68QPT5M600auT6M.SxG
true