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;
}
相关推荐
AIZHINAN2 小时前
Appium 简介
自动化测试·测试工具·appium
吴free8 小时前
mac电脑wireshark快速实现http接口抓包
网络·测试工具·http·wireshark
DeamoTech14 小时前
ESCADA
物联网·测试工具
旷世奇才李先生1 天前
Selenium 安装使用教程
selenium·测试工具
巴里巴气2 天前
对selenium进行浏览器和驱动进行配置Windows | Linux
selenium·测试工具
有趣的我2 天前
wireshark介绍和使用
网络·测试工具·wireshark
草履虫建模2 天前
Postman - API 调试与开发工具 - 标准使用流程
java·测试工具·spring·json·测试用例·postman·集成学习
AIZHINAN3 天前
如何评价 selenium 自动化测试框架搭建?
selenium·测试工具
WIN赢12 天前
PostMan使用
测试工具·lua·postman
百里图书13 天前
颠覆传统接口测试!用 Streamlit + SQLite + GPT 打造可视化自动化平台
自动化测试·测试开发·接口自动化测试·测试工具·接口测试·测试平台·python编程