文章目录

一、概述

一、概述

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

// ------ 导入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;

}

参考链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: