全部 ApiPost使用 后端 前端 接口测试 IOS Android 数据库 2022 测试技术 工具
问答 / 问答详情

[已处理] 我需要用SHA256withRSA算法在预执行脚本生成签名,有什么办法。

下面是我写的脚本,但需要导入外部库。

// 私钥,PEM 格式
const privateKeyPem = `-----BEGIN RSA PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCRuKcPEZrpZsqR
tLcf0NZjallVozXwiGxs+LtbzC3cspkAoohx8czn/NKOHWhwI7dyj1uG0iGDJ9sk
7d9+kGcBl+o3K54ZAUt1JyCnsphZI4Y1Uzi4JVhzLOPZ51Ft5+mqZ4g04dlUus2o
BdByre+Yoy33ZXHzsxfpsZx88HyW6DTVmVQi8bLNcy7UnQqWpEz29jilGq7w9rG1
EgfrC83SVtrVjFzV6fNCwxXaiuKMn1maYMD9cvkU9Zboyhb/Tgn/1mMoqYKqq9QO
/wINFEkgLeFMo/oW1SAW/VefNoQE7/2CUSCi6lwNYYYRGNpIOQ2CnKFth4W3RRZQ
X4Va02Y7AgMBAAECgf81gZfV8KDxEs1OswyKoiQWXPZwe31S1MT7PlmNW2t7nhiQ
Ix32uNKEXFDz3dh7VKIHbpws5PtpLTlKVg26a0tnSmC14U4r4E3UtolHCkzmbiTZ
b7Vj6FKR9+myGT3NHVqvN1TMFiG2+uCI0Zm4giV35nL6ZEVzNk+Rf6X2OleFES+w
Vn4JT1peZ8E+oD2ChdGHi/yF7M8jiavabl3jlAROqZLWrM/rpaOFtErh0+a65AxE
jiEGfDauphFWebAUJT9K7s2ORPd6jDvNFL2d4Psm1l7C3BxpJs6D8iMnv5SQ3yeB
f9nlZXuvzBvWFjTfEDskCVX1FDHK07cCsf/n4PECgYEA1tUJRO0Emp6FucOWa+Tc
WOPadJ5uLMPe1gM43hfkWuG/ravx468KsEgs82oY48T0XbZJl6RsmlouRZHaeKBE
hNjIp1TLNsP3nU+UzQ5o0pjVbhPLc4ycjIMucZK3F2xG8NZlVO8BX5F6r7fkeCsO
MJRDP6WEPeKwelwypCXtOi0CgYEAraVDT42dDiojlrNknlMbfBpIqJn6lRDqE9JA
DbgR6xTeTzPR5HdS2E4T6l/HArUrlrFtOtSg9A+UQQkzok8mlwXh5hJPQbGO3qYM
IsERUwqQOGaEcr1AJ4xP2CgLCbKpz7p7KfHfyINO4j1wLnvAXxkx9Nyrt9c+zWrj
UfPeawcCgYBy9eFV7vetvfKVa6KM7hUzxApcqYMPlWkjYOoHfwWF1JP73a09R6gS
mSzkvPvAtt6FX0yWRziOiH+GXvxn3GuOI2uMj4WHMurIVZOs/278cyiTFSikFrSX
RIOP5xDvCdQUgMYM4zD68SCT83XhEDkxqcUqw+m2LB5/++JlkJ4XqQKBgQCDeDN9
QNffSJJHYC1XHc8aaAAI/wPU5siDF1V9zZZraRJj3vUUSC+GK58yfS984lRNNKph
t2jhQAZcMy5PviOWhlKhUc2GDHwCIK/hhFGskLvep+exw42WI8qz+qVYw1eEOklT
2Zg4BQqtihysZO+iUL4dCRJOD36yIjJX8w678wKBgQCFDfdvATkfOw1K4zhkRJFe
3BxK8UeRVpqUJ53O2uD79jRdstxVfl0xqtwPBi0TyDwiW+Vvf7GIM1J13Y/4c212
jFWcphJ5gJiaz3lrhadKK39HQ16pO2XXzVw5vFT/1pizUiS2bWUVk2mVeyHe9hwC
dA4urZmpYIt3BBW+nifrJA==
-----END RSA PRIVATE KEY-----`;

// 请求体
const requestBody = pm.request.body.raw;
let requestData;

try {
  requestData = JSON.parse(requestBody);
} catch (e) {
  console.error("Failed to parse requestBody:", e.message);
  return;
}

// 构建签名字符串
function processMap(map) {
  return Object.keys(map)
    .sort()
    .map(key => `${key}=${typeof map[key] === "object" ? processMap(map[key]) : map[key]}`)
    .join("&");
}

const stringToSign = processMap(requestData);
console.log("String to sign:", stringToSign);

// 使用 jsrsasign 库生成签名
const KJUR = require("jsrsasign");
const rsa = new KJUR.crypto.Signature({ alg: "SHA256withRSA" });
rsa.init(privateKeyPem);
rsa.updateString(stringToSign);

const signature = KJUR.crypto.Util.encodeBase64(rsa.sign());
console.log("Generated RSA signature:", signature);

// 将签名存储在 Postman 环境变量中
pm.environment.set("signature", signature);

有什么别的办法嘛  

| 0 收藏

1 个回答

我们不支持外部js  可以看看我么内置库https://wiki.apipost.cn/docs/usescript/js

Apipost 私有化火热进行中

撰写答案

只服务于

前后端、移动端、测试人员

提问题 发布您遇到的Bug和问题,上万名大牛和开发者来帮您解决!