挂载全局方法

使用jsencrypt进行rsa加密

原文链接:Js参数RSA加密传输,jsencrypt.js的使用 *
https://www.jb51.net/article/179813.htm
(原文处有一个地方不对,不需要转换+,rsa已经做过base64转码了)

1.安装依赖 npm install jsencrypt 
2.在main.js引入 import { JSEncrypt } from 'jsencrypt' 
3.挂载全局方法
//JSEncrypt加密方法
Vue.prototype.$encryptedData = function(publicKey, data) {
 //new一个对象
 let encrypt = new JSEncrypt()
 //设置公钥
 encrypt.setPublicKey(publicKey)
 //password是要加密的数据,此处不用注意+号,因为rsa自己本身已经base64转码了,不存在+,全部是二进制数据
 let result = encrypt.encrypt(password)
 return result
}
//JSEncrypt解密方法
Vue.prototype.$decryptData = function(privateKey, data) {
 // 新建JSEncrypt对象
 let decrypt = new JSEncrypt()
 // 设置私钥
 decrypt.setPrivateKey(privateKey)
 // 解密数据
 let result = decrypt.decrypt(secretWord)
 return result
}

全局混合

使用yarn安装至Vue项目

yarn add jsencrypt --dep

或者使用npm

npm install jsencrypt --dep

混入

import { JSEncrypt } from 'jsencrypt'
export const RsaMixin = {
 methods: {
  // 加密
  encryptedData(publicKey, data) {
   // 新建JSEncrypt对象
   let encryptor = new JSEncrypt();
   // 设置公钥
   encryptor.setPublicKey(publicKey);
   // 加密数据
   return encryptor.encrypt(data);
  },
  // 解密
  decryptData(privateKey,data){
   // 新建JSEncrypt对象
   let decrypt= new JSEncrypt();
   // 设置私钥
   decrypt.setPrivateKey(privateKey);
   // 解密数据
   decrypt.decrypt(secretWord);
  }
 }
}

引入

<script>
 import InvoiceRecordModal from './modules/InvoiceRecordModal'
 import { RsaMixin } from '@/mixins/RsaMixin'

 export default {
 name: "InvoiceRecordList",
 //此时可以直接调用混入的方法
 mixins:[RsaMixin],
 data(){},
 computed:{}
 }
</script>

封装为单VUE文件中的方法

使用yarn安装至Vue项目

yarn add jsencrypt --dep

或者使用npm

npm install jsencrypt --dep

引入jsencrypt

import { JSEncrypt } from 'jsencrypt'

方法

methods: {
 // 加密
 encryptedData(publicKey, data) {
  // 新建JSEncrypt对象
  let encryptor = new JSEncrypt();
  // 设置公钥
  encryptor.setPublicKey(publicKey);
  // 加密数据
  return encryptor.encrypt(data);
 },
 // 解密
 decryptData(privateKey,data){
  // 新建JSEncrypt对象
  let decrypt= new JSEncrypt();
  // 设置私钥
  decrypt.setPrivateKey(privateKey);
  // 解密数据
  decrypt.decrypt(secretWord);
 }
 }

总结