基于RSA+AES实现前后端(VUE+PHP)参数加密传输

实现原理:

前端篇

引入第三方组件,jsencrypt提供RAS加密,crypto-js提供AES加密

npm install jsencrypt
npm install crypto-js
import CryptoJs from "crypto-js"
import JsEncrypt from "jsencrypt"

export default {
  /**
   * AES加密
   * word 待加密字符串
   * key  十六位十六进制数AES秘钥
   */
  aesEncrypt(word, key){
    let encrypted = CryptoJs.AES.encrypt(CryptoJs.enc.Utf8.parse(word), CryptoJs.enc.Utf8.parse(key), {
      iv: CryptoJs.enc.Utf8.parse("012345679ABCDEF"),
      mode: CryptoJs.mode.CBC,
      padding: CryptoJs.pad.Pkcs7,
    });
  }

  /**
   * RSA加密
   * word 待加密字符串
   * rsaPubKey RSA公钥
   */
  rsaEncrypt(word, rsaPubKey){
    let jse = new JsEncrypt();
    jse.setPublicKey(publicKey);
    return jse.encrypt(word);
  }

  /**
   * AES随机秘钥
   */
  aesRandomKey(){
    let charStr = "012345679abcdefABCDEF";
    let randomKey = "";
    for (var i = 0; i < 16; i++) {
      randomKey += charStr[parseInt(Math.random() * charStr.length)];
    }
    return randomKey;
  }   

  /**
   * RSA公钥,由后端提供或通过接口动态获取
   */
  rsaPubKey(){
    return "xxx";
  }
}

实现

let word = "test";
let aesKey = aesRandomKey();
let rsaPubKey = rsaPubKey();

axios.post("xxx", {
  wordEn: aesEncrypt(word, aesKey), // 参数密文
  aesKeyEn: rsaEncrypt(aesKey, rsaPubKey), // AES秘钥密文
});

基于RSA+AES实现前后端(VUE+PHP)参数加密传输

上一篇:执行npx webpack-dev-server报错: Cannot find module 'webpack-cli/bin/config-yargs'


下一篇:教你在 Kubernetes 上部署 Redis 高可用集群