用户密码加盐加密

使用bcrypt

  bcrypt是一种跨平台的文件加密工具。由它加密的文件可在所有支持的操作系统和处理器上进行转移。它的口令必须是8至56个字符,并将在内部被转化为448位的密钥。(http://www.atool.org/hash.php) 网站,可以直观的看一下加密的算法。

1、用npm 进行安装

 npm install --save bcrypt --registry=https://registry.npm.taobao.org

2、在Schema文件下的js文件引入bcrypt

  const bcrypt=require('bcrypt')

  const SALT_WORK_FACTOR=10 //加盐长度

  用pre每次进行保存时都进行加盐加密的操作

//每次存储数据时都要执行
userSchema.pre('save', function(next){
    //let user = this
    console.log(this)
    bcrypt.genSalt( SALT_WORK_FACTOR,(err,salt)=>{
        if(err) return next(err)
        bcrypt.hash(this.password,salt, (err,hash)=>{
            if(err) return next(err)
            this.password = hash
            next()
        }) 
    })
})

   

原文地址:https://www.cnblogs.com/websunny/p/9962172.html