0%

jsencrypt-RSA加密

RSA加密工具,从后台获取公钥对数据进行加密再传输,保护敏感数据。

安装

加密工具,jsencrypt。参考博客:传送门

cdn引入:

1
<script src="http://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>

npm或cnpm下载:

1
2
3
4
//1.安装依赖   
cnpm install jsencrypt --save
//在main.js引入
import { JSEncrypt } from 'jsencrypt'

使用

配置

某项目中jsencrypt的配置如下(main.js文件):

  • 加密函数,挂载到VUE原形上(prototype属性可以向对象中添加属性或方法),后续通过$encryptedData调用。
  • 获取公钥函数,挂载到VUE原形上,后续通过$getPublicKey调用。
  • 获取到的公钥,保存在$publickey中,挂载在VUE原形上。
  • 注意:要使用elementui的弹窗组件(获取公钥函数中有使用到),需要保证下边的配置在elementui的import之后。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//在main.js中挂载全局方法:
//使用时调用Vue的函数[this|Vue].$encryptedData即可。
Vue.prototype.$encryptedData = function(publicKey, data) {//参数为公钥、待加密的数据
//new一个对象
let encrypt = new JSEncrypt();
//设置公钥
encrypt.setPublicKey(publicKey);
//data是要加密的数据
let result = encrypt.encrypt(data);
return result
}
Vue.prototype.$getPublicKey = function() {//获取RSA公钥,挂载到Vue上,可通过this.$getPublicKey调用
axios({//在前边得将Axios导入为axios,这里才可以调用
method: 'get',
url: '/publickey',//前边得配置了全局URL才能正常发起Ajax请求
responseType: 'text'
})
.then(response => {
Vue.prototype.$publickey = response.data;//将获取到得公钥,又保存在Vue原形上的自定义变量$publickey上
})
.catch(err => {
elementui.Message.error(err.message);//在前边得将ElementUI导入为elementui,这里才可以调用
});
}

vue页面应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//1.在钩子函数created中向服务器获取公钥:
created() {
this.$getPublicKey();
}

//2.在发起Ajax请求时,将用户名和密码加密再发送给服务器:
//登录
this.$http({
method: 'post',
url: '/accounts/token',
responseType: 'json',
data: {
username: this.$encryptedData(this.$publickey, this.loginForm.username.trim()),
password: this.$encryptedData(this.$publickey, this.loginForm.password.trim())
}
})
.then(respon => { //Ajax 请求成功
this.loading = false; //关闭 加载动画
var data = respon.data;
if (data.meta.status != "200") {
this.shake(this.isShakeForm); //表单 摇晃动画
this.$message.error(data.meta.msg);
} else {
this.$message.success('登录成功');
// 1、将登陆成功之后的token, 保存到客户端的sessionStorage中; localStorage中是持久化的保存
// 1.1 项目中出现了登录之外的其他API接口,必须在登陆之后才能访问
// 1.2 token 只应在当前网站打开期间生效,所以将token保存在sessionStorage中
window.sessionStorage.setItem('token', data.token);
window.sessionStorage.setItem('account', JSON.stringify(data.account));

// 2、通过编程式导航跳转到后台主页, 路由地址为:/home
this.$router.push('/home');
}
})
.catch(err => { //Ajax 请求出错
this.loading = false; //关闭 加载动画
this.$message.error(err.message);
this.shake(this.isShakeForm); //表单 摇晃动画
});
若图片不能正常显示,请在浏览器中打开

欢迎关注我的其它发布渠道