You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript读取外部JSON遍历生成LibSodium加密值的实现方法

完全可以通过forEach实现批量加密,具体实现如下:


核心思路

  1. 引入Node.js内置fs模块读取本地JSON文件
  2. 将原有单组加密逻辑封装为可复用函数
  3. 解析JSON得到数组后通过forEach遍历每一组键值对,调用加密函数生成对应结果

完整可运行代码

const sodium = require('tweetsodium');
const fs = require('fs');
const path = require('path');

// 加密逻辑封装,传入原始key和value,返回base64格式加密结果
function encrypt(rawKey, rawValue) {
  const messageBytes = Buffer.from(rawValue);
  const keyBytes = Buffer.from(rawKey, 'base64');
  const encryptedBytes = sodium.seal(messageBytes, keyBytes);
  return Buffer.from(encryptedBytes).toString('base64');
}

// 读取外部JSON文件,替换为你实际的文件路径
const jsonContent = fs.readFileSync(path.join(__dirname, '你的配置文件.json'), 'utf-8');
// 注意:你给出的JSON示例末尾多了一个分号,标准JSON不支持该写法,实际存储时需要删除,否则解析会报错
const configList = JSON.parse(jsonContent);

// 批量遍历处理
configList.forEach((item, idx) => {
  const encryptedResult = encrypt(item.key, item.value);
  console.log(`===== 第${idx+1}组数据 =====`);
  console.log('原始key:', item.key);
  console.log('原始value:', item.value);
  console.log('加密结果:', encryptedResult, '\n');
});

补充说明

  • 如果JSON文件体积较大,可替换为fs.readFile异步读取避免阻塞
  • 输出格式可根据你的需求调整,也可以把所有加密结果整理为新的JSON文件写入本地存储

内容的提问来源于stack exchange,提问作者Iamppmz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:51:02