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;
}
相关推荐
tomorrow.hello11 小时前
Java并发测试工具
java·开发语言·测试工具
weixin_4567325913 小时前
tcpdump交叉编译
网络·测试工具·tcpdump
chao_78913 小时前
frame 与新窗口切换操作【selenium 】
前端·javascript·css·selenium·测试工具·自动化·html
小王的饲养员1 天前
Apipost 与 Apifox 数据库功能对比:深入解析与应用场景分析
大数据·数据库·人工智能·后端·postman
funnycoffee1231 天前
Cisco ACI 生成Postman CSV 脚本场景
postman·cisco aci
sunshine__sun2 天前
web网页用postman调用接口测试(超简单方法)
测试工具·postman
一筐大白菜啊2 天前
【工具】什么软件识别重复数字?
测试工具
随便写个昵称2 天前
selenium中xpath的用法大全
selenium·测试工具
随便写个昵称2 天前
selenium中find_element()用法进行元素定位
selenium·测试工具