【Vite+Ts+Vue3】使用Crypto-js封装AES加密

安装依赖

cnpm install crypto-js --save

项目创建secret.ts文件

import CryptoJS from "crypto-js";

// 必须为16、24、32位
const KEY = "4564564564564564";
const IV = "4564564564564564";

/**
 * AES加密 :字符串 key iv  返回base64
 */
export const Encrypt = (word: any, keyStr = KEY, ivStr = IV): any => {
  const key = CryptoJS.enc.Utf8.parse(keyStr);
  const iv = CryptoJS.enc.Utf8.parse(ivStr);
  const srcs = CryptoJS.enc.Utf8.parse(word);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding,
  });
  return encrypted.toString();
};

/**
 * AES 解密 :字符串 key iv  返回base64
 *
 * @return {string}
 */
export const Decrypt = (word: any, keyStr = KEY, ivStr = IV): any => {
  const key = CryptoJS.enc.Utf8.parse(keyStr);
  const iv = CryptoJS.enc.Utf8.parse(ivStr);
  const decrypt = CryptoJS.AES.decrypt(word, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding,
  });
  return CryptoJS.enc.Utf8.stringify(decrypt);
};

项目中使用

import { Encrypt, Decrypt } from "@/utils/secret.ts";

加密:
Encrypt(token)
解密:
Decrypt(token)

你可能感兴趣的:(前端,Vue.js,javascript,typescript,vue.js)