vue对于路由参数进行加密处理

实现方式:stringifyQueryparseQuery

// src\utils\encryption.js
// 按需引入 CryptoJS 需要的组件
const CryptoJS = require("crypto-js/core");
const Latin1 = require("crypto-js/enc-latin1");
const AES = require("crypto-js/aes");
const ZeroPadding = require("crypto-js/pad-zeropadding");
const Utf8 = require("crypto-js/enc-utf8");
const Base64 = require("crypto-js/enc-base64");
/*
 * 加密 解密
 */
const baseCryptoCode = "********"; // 这个私钥每个项目指定一个唯一。更换密钥,请确认16位

const getKeyHex = (cryptoCode) => Latin1.parse(cryptoCode || baseCryptoCode);

const getIvHex = () => Latin1.parse(baseCryptoCode);

/**
 * 加密
 * @param {String} key
 * @param {String} cryptoCode
 * @returns {string}
 */
export const getEncrypt = (key, cryptoCode) => {
  let keyHex = getKeyHex(cryptoCode);
  let ivHex = getIvHex();
  try {
    key = JSON.stringify(key);
  } catch (e) {
    console.warn(e);
  }
  return AES.encrypt(key, keyHex, {
    mode: CryptoJS.mode.CBC,
    padding: ZeroPadding,
    iv: ivHex,
  }).toString();
};

/**
 * 加密后转base64
 * @param {String}} key
 * @param {String} cryptoCode
 */
export const getEncryptToBase64 = (key, cryptoCode) => {
  let encryptStr = getEncrypt(key, cryptoCode);
  let wordArray = Utf8.parse(encryptStr);
  return Base64.stringify(wordArray);
};

/**
 * 解密
 * @param data
 * @returns {string}
 */
export const getDecrypt = (data) => {
  let keyHex = getKeyHex();
  let ivHex = getIvHex();
  let decrypted = AES.decrypt(
    {
      ciphertext: Base64.parse(data),
    },
    keyHex,
    {
      mode: CryptoJS.mode.CBC,
      padding: ZeroPadding,
      iv: ivHex,
    }
  ).toString(Utf8);
  try {
    decrypted = JSON.parse(decrypted);
  } catch (e) {
    console.warn(e);
  }
  return decrypted;
};

/**
 * 对base64数据解密  先解析base64,在做解密
 * @param {String} data
 * @returns {string}
 */
export const getDecryptByBase64 = (data) => {
  let parsedWordArray = Base64.parse(data);
  let decryptStr = parsedWordArray.toString(Utf8);
  return getDecrypt(decryptStr);
};

 

// src\utils\query.js
import {
  getEncryptToBase64 as encrypt,
  getDecryptByBase64 as decrypt,
} from "./encryption";
const encodeReserveRE = /[!'()*]/g;
const encodeReserveReplacer = (c) => "%" + c.charCodeAt(0).toString(16);
const commaRE = /%2C/g;

const encode = (str) =>
  encodeURIComponent(str)
    .replace(encodeReserveRE, encodeReserveReplacer)
    .replace(commaRE, ",");

const decode = decodeURIComponent;

/**
 * 判断字符串是否是base64
 * @param { string } str
 * @returns { boolean }
 */
function isBase64(str) {
  if (str === "" || str.trim() === "") {
    return false;
  }
  try {
    return btoa(atob(str)) == str;
  } catch (err) {
    return false;
  }
}

/**
 * 序列化对象 并加密
 * @param {Object} obj
 */
export const stringifyQuery = (obj) => {
  const res = obj
    ? Object.keys(obj)
        .map((key) => {
          const val = obj[key];

          if (val === undefined) {
            return "";
          }

          if (val === null) {
            return encode(key);
          }

          if (Array.isArray(val)) {
            const result = [];
            val.forEach((val2) => {
              if (val2 === undefined) {
                return;
              }
              if (val2 === null) {
                result.push(encode(key));
              } else {
                result.push(encode(key) + "=" + encode(val2));
              }
            });
            return result.join("&");
          }

          return encode(key) + "=" + encode(val);
        })
        .filter((x) => x.length > 0)
        .join("&")
    : null;

  return res ? `?${encrypt(res)}` : "";
};

/**
 * 解密  反序列化字符串参数
 * @param {String}} query
 */
export const parseQuery = (query) => {
  const res = {};

  query = query.trim().replace(/^(\?|#|&)/, "");

  if (!query) {
    return res;
  }

  // 解密
  query = isBase64(query) ? decrypt(query) : query;

  query.split("&").forEach((param) => {
    const parts = param.replace(/\+/g, " ").split("=");
    const key = decode(parts.shift());
    const val = parts.length > 0 ? decode(parts.join("=")) : null;

    if (res[key] === undefined) {
      res[key] = val;
    } else if (Array.isArray(res[key])) {
      res[key].push(val);
    } else {
      res[key] = [res[key], val];
    }
  });

  return res;
};

  

在router/index.js添加一下代码:

import { stringifyQuery, parseQuery } from "@/utils/query";
const routes = [];
const router = new VueRouter({
  mode: "history",
  stringifyQuery: stringifyQuery, // 序列化query参数
  parseQuery: parseQuery, // 反序列化query参数
  routes,
});
export default router;

 

以下加密的效果:

 

加密:

 

解密后:

 

 

 

posted @ 2023-01-09 17:51  zaijinyang  阅读(518)  评论(1编辑  收藏  举报