前端 des 加密解密 zlib 压缩解压 实测可用 vite编译模式下需要特殊处理 在教程中

前后端协商使用des加密 前端使用crypto-js这个库 (一般加密解密配合压缩解压使用)

1. 加密解密代码

import CryptoJS from 'crypto-js'; // 加密解密
import { zip, unzip } from './zlip'; // 压缩解压

// key iv前后端统一指定(一般后端决定)
const key = '****',
  iv = '*****',
  keyHex = CryptoJS.enc.Utf8.parse(key),
  ivHex = CryptoJS.enc.Utf8.parse(iv),
  // 加密
  encryptDES = async message => {
    // 压缩成base64格式 防止中文出现问题
    const res = await zip(message);
    // 压缩失败
    if (!res) return false;
    // CryptoJS.DES 使用des加密
    const encrypted = CryptoJS.DES.encrypt(res, keyHex, {
      iv: ivHex,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    // 返回base64格式的string化
    // encrypted.ciphertext.toString() 前端默认使用的是hex格式 后端使用的是base64格式 所以要转化
    return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
  },
  // 解密
  decryptDES = ciphertext => {
    const decrypted = CryptoJS.DES.decrypt(
      {
        // 后端加密返回base64格式 所以用base64格式处理
        ciphertext: CryptoJS.enc.Base64.parse(ciphertext),
      },
      keyHex,
      {
        iv: ivHex,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
      },
    );
    // 解密出来是经过zlip压缩成base64格式的 所以要解压
    return unzip(decrypted.toString(CryptoJS.enc.Utf8));
  };

export { encryptDES, decryptDES };



2. 压缩解压代码

vite 编译模式下 zlib这个库不能用 Buffer也不能用需要解决一下:修改 vite.config.js 文件
yarn add @esbuild-plugins/node-globals-polyfill
yarn add @esbuild-plugins/node-modules-polyfill
rollup-plugin-node-polyfills 这个库是 @esbuild-plugins/node-modules-polyfill自带的 不用安装
yarn add buffer

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vuejsx from "@vue/babel-plugin-jsx";
// node polyfill 需要安装这两个库
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'
import rollupNodePolyFill from 'rollup-plugin-node-polyfills'

const path = require("path");

export default defineConfig({
  hmr: true, // 热更新
  plugins: [
    vue(),
    vuejsx({})
  ],
  resolve: {
    // 配置路径别名
    alias: {
      "@": path.resolve(__dirname, "./src"),
      util: 'rollup-plugin-node-polyfills/polyfills/util',
      sys: 'util',
      events: 'rollup-plugin-node-polyfills/polyfills/events',
      stream: 'rollup-plugin-node-polyfills/polyfills/stream',
      path: 'rollup-plugin-node-polyfills/polyfills/path',
      querystring: 'rollup-plugin-node-polyfills/polyfills/qs',
      punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',
      url: 'rollup-plugin-node-polyfills/polyfills/url',
      string_decoder: 'rollup-plugin-node-polyfills/polyfills/string-decoder',
      http: 'rollup-plugin-node-polyfills/polyfills/http',
      https: 'rollup-plugin-node-polyfills/polyfills/http',
      os: 'rollup-plugin-node-polyfills/polyfills/os',
      assert: 'rollup-plugin-node-polyfills/polyfills/assert',
      constants: 'rollup-plugin-node-polyfills/polyfills/constants',
      _stream_duplex: 'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
      _stream_passthrough: 'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
      _stream_readable: 'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
      _stream_writable: 'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
      _stream_transform: 'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
      timers: 'rollup-plugin-node-polyfills/polyfills/timers',
      console: 'rollup-plugin-node-polyfills/polyfills/console',
      vm: 'rollup-plugin-node-polyfills/polyfills/vm',
      zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
      tty: 'rollup-plugin-node-polyfills/polyfills/tty',
      domain: 'rollup-plugin-node-polyfills/polyfills/domain',
      buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6',
      process: 'rollup-plugin-node-polyfills/polyfills/process-es6'
    },
  },
  optimizeDeps: {
    esbuildOptions: {
      // Node.js global to browser globalThis
      define: {
        global: 'globalThis'
      },
      // Enable esbuild polyfill plugins
      plugins: [
        NodeGlobalsPolyfillPlugin({
          process: true,
          buffer: true
        }),
        NodeModulesPolyfillPlugin()
      ]
    }
  },
  build: {
    rollupOptions: {
      plugins: [
        // Enable rollup polyfills plugin
        // used during production bundling
        rollupNodePolyFill()
      ]
    }
  }
});

import zlib from 'zlib';
import { Buffer } from 'buffer'

//压缩
const zip = value => {
    return new Promise((resolve, reject) => {
      zlib.gzip(value, (err, buffer) => {
        if (err) {
          console.error('压缩错误:', err);
          reject(false);
        }
        // 压缩为base64格式编码(防止中文出现问题)
        resolve(buffer.toString('base64'));
      });
    });
  },
  // 解压
  unzip = value => {
    // 后端返回的是base64编码格式的string格式 所以要base64转化一下
    const buffer = Buffer.from(value, 'base64');
    return new Promise((resolve, reject) => {
      zlib.gunzip(buffer, (err, buffer) => {
        if (err) {
          console.error('解压错误:', err);
          reject(false);
        }
        // 解压出string的格式 因为前端需要string
        if (buffer) resolve(buffer.toString());
      });
    });
  };
export { zip, unzip };
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值