前端使用yaml配置文件与加密解密小工具

929 阅读2分钟

最近有个需要对接权限业务,前端需要加一堆配置,领导要求使用yaml做配置文件与后端保持一致,并且文件配置需要使用JSEncrypt加密 这里有两个问题:

  • 1.前端如何读取yaml文件,并分为不同开发环境
  • 2.因为这里的配置文件都是加密的,由于运维需要定期去改配置文件,因为加密他也不知道改成啥样子 针对这两个问题,第一点在前端中可以读取yaml文件,需要使用js-yaml这个工具库,并使用config可以合并不同环境下变量

加解密小工具效果 recording.gif 安装以下几个库

pnpm add js-yaml config cross-env

image.png

image.png

写一个配置文件用于获取yaml文件数据,并将不同环境配置文件进行合并

image.png

这样配置文件yaml就可以读取了 下面第二个问题,我想到是写一个脚本去做加密解密,代码如下 需要安装一个库

pnpm add node-jsencrypt

// 导入必要的库
import readline from 'readline';
import JSEncrypt from 'node-jsencrypt';

// 创建一个接口以便读取控制台输入
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

//公钥
const decrypt = new JSEncrypt();
const PRIVATE_KEY =
  "xxxxx";
decrypt.setPublicKey(
  "-----xx xx xx----" +
    PRIVATE_KEY +
    "-----xx xx xx-----"
);

// 提示用户选择操作类型
function askForOperation() {
  console.log("请选择操作: (1) 数据加密 (2) 数据解密 (3) 退出");
  process.stdout.write(
    "默认操作为数据加密,请直接输入要加密的数据或选择其他操作:"
  );

  rl.question("", (input) => {
    if (input.trim() === "") {
      // If user just presses Enter, default to encryption
      askForInput();
    } else {
      // Otherwise, process the input as an operation
      const operation = input.trim();
      if (operation === "1") {
        askForInput();
      } else if (operation === "2") {
        askForDecryption();
      } else if (operation === "3") {
        exitForDecryption();
      } else {
        console.log("无效选择,请重新选择。");
        askForOperation();
      }
    }
  });
}

// 定义递归函数以便重复读取输入并加密
function askForInput() {
  rl.question("请输入要加密的数据: ", (input) => {
    // 使用JSEncrypt加密数据
    const encrypted = decrypt.encrypt(input);
    // 输出加密后的数据
    console.log("加密后的数据: ", encrypted);
    askForOperation();
  });
}

function askForDecryption() {
  rl.question("请输入要解密的数据: ", (input) => {
    // 使用JSEncrypt加密数据
    const encrypted = decrypt.decrypt(input);
    // 输出加密后的数据
    console.log("解密后的数据: ", encrypted);
    askForOperation();
  });
}

function exitForDecryption() {
  console.log("程序已退出。");
  rl.close(); // 关闭 readline 接口
  process.exit(0); // 退出 Node.js 进程
}
// 初始调用
askForOperation();

写完代码用webpack打包一下,本来使用rollup,但是不熟练,放弃了,这里用webpack

image.png 找到对应的index.js文件,使用node index.js