Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

eggjs密码加密

策略

  • 前端先用md5加密一遍,然后传到后端

  • 后端再用哈希函数再加密一遍,放到数据库

  • 其实现在都是手机号验证码登录,大家都不记密码了。。。

前端加密

  • 安装crypto-js

    cnpm install -S crypto-js
    

后端加密

  • 安装egg-bcrypt加密插件

    cnpm install -S egg-bcrypt
    
  • 打开config/plugin.js,找到如下内容

    module.exports = {
        //里面添加下面四行
        bcrypt : {
            enable: true,
            package: 'egg-bcrypt',
        }
    }
    
  • config/config.default.js中,指定saltRounds

    exports.bcrypt = {
      saltRounds: 10 
    }
    
    • 默认就是10
  • 在service中使用

    • 加密
      const 哈希加密后的密码 = await this.ctx.genHash(密码)
      
    • 验证
      const 结果 = await this.ctx.compare(密码, 哈希加密后的密码)