/**
* npm install jsencrypt -S
* @param getPublicKey 获取到的公钥,一般由后端返回,我们可以在点击提交按钮时发送ajax请求拿到该返回的公钥
* @param data 我们需要加密的数据,通过实例化对象操作之后返回一段新的加密码,然后将其作为参数发送给后端即可
* @returns {PromiseLike<ArrayBuffer>}
*/
function encryptData(getPublicKey, data) {
// 实例化对象
let encrypt = new JsEncrypt();
// 设置公钥
encrypt.setPublicKey(getPublicKey);
// 返回加密的数据
return encrypt.encrypt(data);
}
<template>
</template>
<script>
import JsEncrypt from 'jsencrypt'
import axios from 'axios'
export default {
data() {
return {
username: 'hello',
password: ''
}
},
methods: {
encryptData(getPublicKey, data) {
// 实例化对象
let encrypt = new JsEncrypt();
// 设置公钥
encrypt.setPublicKey(getPublicKey);
// 返回加密的数据
return encrypt.encrypt(data);
},
submit() {
axios({
method: 'post',
url: '',
}).then(res => {
// res为后端返回的key,如同下面这样
// let res = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCa+VHPOwxi0re/GhWApLl6WQMoTKazQsPp66AD8CKt2TaPrwv+dDFdQ5jP9xRbalGhLhEBlDq20oOCuIwWAI7/s0QTTvjYIBd+yWKzuRp0E+Qe7DqIE0pMrTi/ELkqibehYIvJ4sIEM+Wj9R007WT/64vGG/FaPsK9RsZiGShOAQIDAQAB'
let password = this.encryptData(res, password);
axios({
method: 'post',
url: '',
data: {
username: this.username,
password: password
}
}).then(ress => {
console.log(ress);
})
})
}
}
}
</script>
<style>
</style>