vue使用JSEncrypt實現rsa加密及掛載方法

掛載全局方法

使用jsencrypt進行rsa加密

原文連接:Js參數RSA加密傳輸,jsencrypt.js的使用 - CSDN博客*
https://blog.csdn.net/p312011150/article/details/80264144
(原文處有一個地方不對,不須要轉換+,rsa已經作過base64轉碼了)vue

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 --depnpm

或者使用npm

npm install jsencrypt --depsegmentfault

混入

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.net

引入jsencrypt

import { JSEncrypt } from 'jsencrypt'prototype

方法

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);
    }
  }

站在巨人的肩膀上摘蘋果:

連接:https://www.jianshu.com/p/084548516410 ()
https://segmentfault.com/a/1190000018896698 (全局混入以及單文件方法)
https://www.jianshu.com/p/084548516410 (全局註冊)code

相關文章
相關標籤/搜索