最近在项目的时候遇到一个问题,需要将项目中的页面提供给外部系统,外部系统嵌套页面,刚开始密码是明文提供给外部系统,可想而知如果正式环境使用明文密码,肯定会存在隐患,这个时候我就在想怎么将密码加密,于是就用了jsencrypt.js进行RSA加密解密。如果密码是URL上还需要用encodeURIComponent进行编码。
以下是VUE中使用jsencrypt.js的步骤:
1、安装jsencrypt
npm install jsencrypt
2、vue中引用jsencrypt
第一种:import { JSEncrypt } from 'jsencrypt'
第二种:import JSEncrypt from 'jsencrypt'
3、代码示例
<script>
import { JSEncrypt } from 'jsencrypt'
export default {
name: 'HelloWorld',
data() {
return {
// 公钥
publicKey: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCoSgdHnJMibGDFIMmge4YjdhZh'
+'y6l+MWUIVGhA3S0uGRvnYd38+A6DGxKDnjmwez9qKzyNw5xFxd1WyDqc6LgY6jFF'
+'+MqQucPhi0So9VN7cTdotmTNUtXN7VY9nbD6whZwK+hhD8doT3frhXYvi9TU3CUP'
+'McbG8YPHJwyhEbT4jQIDAQAB',
// 私钥
privateKey: 'MIICXAIBAAKBgQCoSgdHnJMibGDFIMmge4YjdhZhy6l+MWUIVGhA3S0uGRvnYd38'
+ '+A6DGxKDnjmwez9qKzyNw5xFxd1WyDqc6LgY6jFF+MqQucPhi0So9VN7cTdotmTN'
+ 'UtXN7VY9nbD6whZwK+hhD8doT3frhXYvi9TU3CUPMcbG8YPHJwyhEbT4jQIDAQAB'
+ 'AoGAcErFRMFzZBrRD3hrUYxa2zqmgKb2999ZvQ8laXKr/QCAIAqrp2qVtGHSHsTr'
+ 'VZlHnT4wb5/AnMYEhS2h/qVCgTYiLmgg5v5hFvAlwQ+nhynZoDPk9cJF8/9wOIz3'
+ 'JEV/m80219/St78djqXocuYD8/ZnuZiYkUN72VjxnXn2Y/kCQQDsN56NWhEKLuKP'
+ 'eBFVF7CJ67LA/wqxVsKjqfIUEVgGo/duc3u3IEHiRVD7+sgHMm2bAtdsstww6PNw'
+ 'TYZNJ8HTAkEAtmIQi78W48/VcoQxf6hqpGnw6YfAUS38j/rDeDQcqGMLWG82Bg9M'
+ 'EcW3/H9Aa/LQwUgnBnSarftzMs0R6zmAHwJAL5SwgkZ/Ii75ge6shxhjfhSVCB0X'
+ 'eUtBn5fu5C3uLkA+6eenJub/fmV5/5evTQvSWiQDYqjQg6WYy6lCAS6d8wJBAKyC'
+ 'Y04biCYhPq7b1Qn/nic3wdTSP5lJmxwAwAUhnX20eVXDk2D19SjWUKn3H1M70DMR'
+ '8T/M6UXpklQZ3noU4FcCQDAoMQrKsaRDmiW6L+Qjw3cOCpL0RGfsNGl5V6T4wjoe'
+ 'rNrwTjp4VhKNTTl+y7xdgeZiFFcqYie4lxRj/mmTnb4=',
}
},
mounted() {
this.test();
},
methods: {
// 使用公钥 加密
getEncrypt(data) {
let encrypt = new JSEncrypt();
// 设置公钥
encrypt.setPublicKey(this.publicKey);
return encrypt.encrypt(data);
},
// 使用私钥 解密
getDecrypt(data) {
let decrypt = new JSEncrypt();
// 设置私钥
decrypt.setPrivateKey(this.privateKey);
return decrypt.decrypt(data);
},
test() {
const encrypt = this.getEncrypt('123456');
console.log("加密后:" + encrypt);
const decrypt = this.getDecrypt(encrypt);
console.log("解密后:" + decrypt)
}
}
}
</script>
4、运行结果