安装依赖
npm i bcrypt
bcrypt加密方案
加密
const bcrypt = require('bcrypt')const SALT_ROUNDS = 10module.exports.bcryptPassword = (password) => {return new Promise((resolve,reject) => {bcrypt.hash(password,SALT_ROUNDS,(err,encrypted) => {if(err)return reject(err)resolve(encrypted)})})}
密码比对
const matchPassword = (oldHashPwd,password)=>{return new Promise(async (resolve,reject)=>{const match = await bcrypt.compare(password,oldHashPwd)console.log(match);})}module.exports = {hashPassword,matchPassword}
测试
async function test() {const pass = 'abc'const bcryptPWD = await bcryptPassword(pass)console.log("bcryptPWD:",bcryptPWD);const match = await matchPassword(bcryptPWD,'abc')console.log("Password matches:",match);}test()
错误解决
方案一:
npm install -g node-gypnpm install --global --production windows-build-toolsnpm install bcrypt -S
方案二:
npm install bcryptjs -Slet bcrypt=require(‘bcryptjs’)
[
](https://blog.csdn.net/weixin_42768220/article/details/104526802)
