Postman 的 Pre-request Script 使用RSA加解密

文章目录

一、概述

Postman内置的Js不支持进行RSA加解密,所以需要引入forgeJS来实现。在 Pre-request Script使用以下脚本:

bash 复制代码
// ------ 导入RSA ------
if (!pm.globals.has("forgeJS")) {
    pm.sendRequest("https://raw.githubusercontent.com/loveiset/RSAForPostman/master/forge.js", (err, res) => {
        if (!err) {
            pm.globals.set("forgeJS", res.text());
            executeRSAOperations();
        }
    });
} else {
    executeRSAOperations();
}

function executeRSAOperations() {
    // 引入 forge 库
    eval(pm.globals.get("forgeJS"));

    // 原始 JSON 数据
    const jsonData = {
        "key1": "value1",
        "key2": "value2"
    };

    // 将 JSON 数据转换为字符串
    const jsonString = JSON.stringify(jsonData);

    // RSA 公钥
    const publicKeyPem = `-----BEGIN PUBLIC KEY-----
    公钥内容
    -----END PUBLIC KEY-----`;

    // RSA 私钥
    const privateKeyPem = `-----BEGIN PRIVATE KEY-----
    私钥内容
    -----END PRIVATE KEY-----`;

    // 使用公钥进行 RSA 加密
    const publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
    const encryptedBytes = publicKey.encrypt(forge.util.encodeUtf8(jsonString));
    const encryptedData = forge.util.encode64(encryptedBytes);

    // 使用私钥进行 RSA 解密
    const privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
    const decryptedBytes = privateKey.decrypt(forge.util.decode64(encryptedData));
    const decryptedData = forge.util.decodeUtf8(decryptedBytes);

    // 输出加密和解密结果
    console.log("加密后数据:", encryptedData);
    console.log("解密后数据:", decryptedData);

    // 更新请求的 Body 数据为加密后的内容
    pm.request.body.raw = encryptedData;
}
相关推荐
火云代理2 天前
同一个网站,有的网络能打开、有的打不开?认识 IPv4 与 IPv6 的访问差异
服务器·网络·网络协议·tcp/ip·测试工具·php·状态模式
freejackman7 天前
【工程化】从“单兵作战”到“多引擎架构”:基于门面模式的重构实战
大数据·数据库·hive·sql·测试工具·设计模式·架构
坐吃山猪7 天前
Python22-PostMan调试MCP
测试工具·postman·mcp
测试界的小码农8 天前
【 AI Agent 软件测试实战(05):任务规划与状态管理,让 Agent 学会拆解复杂测试任务】
人工智能·测试工具
和粒科技9 天前
热重分析仪TG 309 Libra Classic
测试工具
光谱SpectrAI11 天前
打开 Postman 会改 Codex?Windows 上 4 处都没有
postman
yz_aiks12 天前
Postman 自动给 Claude Code、Codex、Cursor 装插件怎么查和卸载:本机实测 5 处痕迹(Postman 12.34)
安全·postman·ai编程·开发工具·claude code
螺丝钉tina15 天前
[Playwright] [02]常用命令与调试:Debug UI、Mode和 Trace Viewer
开发语言·javascript·测试工具·ui·自动化
梧桐16816 天前
14天、31个缺陷、28个测试脚本—用 Claude Code 完成第三方软件测试
人工智能·测试工具
mewowaBc17 天前
postman使用细则
测试工具·postman·偏差