Egg(四)数据加解密之crypto
crypto插件官网
1.安装插件
npm install crypto --save
2.配置文件
配置路径 config / config.default.js
secret参数可以在配置的时候随意修改,项目运行后尽可能不要再次修改
config.crypto = { secret: 'fdgw@45nca052d12adssa23w_3e6d7ksh2!#@3nxjdas*_672' };
3.使用
举例:将密码加密并保存到数据库
文件路径:app/model/user.js,因为我的用户相关的模型放在此文件内
'use strict';
const crypto = require('crypto'); //引入加密组件
module.exports = app => {
const { STRING,INTEGER, DATE } = app.Sequelize;
const User = app.model.define('user',{
id:{
type:INTEGER(20).UNSIGNED, //UNSIGNED代表无符号
primaryKey:true, //主键
autoIncrement:true //自动递增
},
username:{
type:STRING(30),
allowNull:false, //是否允许为空
defaultValue:'', //默认值为空
comment:'用户名称', //备注
unique:false //是否是唯一的
},
password:{
type:STRING(200),
allowNull:false,
defaultValue:'',
//密码加密
set(val){
const hmac = crypto.createHash("sha256", app.config.crypto.secret);
hmac.update(val);
let hash = hmac.digest("hex");
this.setDataValue('password',hash);
}
},
avatar_url:{
type:STRING(200),
allowNull:false,
defaultValue:''
},
phone:{
type:STRING(11),
allowNull:true, //是否允许为空
defaultValue:'', //默认值为空
comment:'手机号', //备注
unique:true //是否是唯一的
},
vip:{
type:INTEGER(1),
allowNull:true, //是否允许为空
defaultValue:0, //默认值为空
comment:'vip', //备注
unique:false //是否是唯一的
},
created_at:DATE,
updated_at:{
type:DATE,
//转换成时间戳
get(){
const val = this.getDataValue('updated_at');
return (new Date(val)).getTime();
}
}
});
//查询用户
return User;
}
4.验证思路
首先将前台传过来的密码进行加密,然后在和数据库中得到的密码进行比对