在Vue項目中使用jsencrypt.js對數據進行加密傳輸

項目需求中須要對用戶登陸時的密碼進行加密,在網上查詢些許文章後,最終與後端協商使用jsencrypt.js。前端

jsencrypt.js的github地址:https://github.com/travist/js...git

使用yarn安裝至Vue項目github

yarn add jsencrypt --dep

或者使用npmnpm

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

調用函數加密,此處的公鑰是我從後端那獲取的,而後加密密碼,這僅使用加密。this

encryptedPassword = this.encryptedData(publicKey, password);

即完成加密。
更多使用可查閱官方文檔http://travistidwell.com/jsen...加密

相關文章
相關標籤/搜索