系統城裝機大師 - 唯一官網:www.farandoo.com!

當前位置:首頁 > 網絡編程 > JavaScript > 詳細頁面

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

時間:2020-02-07來源:系統城作者:電腦系統城

掛載全局方法

使用jsencrypt進行rsa加密

原文鏈接:Js參數RSA加密傳輸,jsencrypt.js的使用 - CSDN博客*
https://blog.csdn.net/p312011150/article/details/80264144
(原文處有一個地方不對,不需要轉換+,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);
    }
  }
分享到:

相關信息

系統教程欄目

欄目熱門教程

人氣教程排行

站長推薦

熱門系統下載

jlzzjlzz亚洲乱熟在线播放