PostMan请求参数RSA加密
· 3 min read
背景
离线环境某API请求参数需要进行RSA加密,postman脚本默认不自带RSA加密环境。
看了网上的博客,大多是请求forge.js,通过调用forge.js脚本进行RSA加密
经过多次验证,自己也记录一下
准备forge.js脚本
离线环境可以下载forge.js 文件,通过evel()函数引用
在线环境可以直接在postman脚本中通过pm.sendRequest获取
https://raw.githubusercontent.com/loveiset/RSAForPostman/master/forge.js
在线环境加密
通过pm.sendRequest获取在线的forge.js脚本,并将文本保存在本地变量中,正常获取后,可以将pm.sendRequert代码注释。
// // if(!pm.environment.has("forgeJS")){
pm.sendRequest("https://raw.githubusercontent.com/loveiset/RSAForPostman/master/forge.js", function (err, res) {
if (err) {
console.log("hellworld")
console.log(err);
} else {
// console.log(res.text())
pm.environment.set("forgeJS", res.text());
}
})
// }
//引用forgeJS
eval(pm.environment.get("forgeJS"));
//获取公钥,可以提前把完整的公钥存入encryptKey变量中
const pubKey = pm.environment.get("encryptKey");
const publicKey = forge.pki.publicKeyFromPem(pubKey);
//加密用户名
const encryptedUser = forge.util.encode64(
publicKey.encrypt("用户名", 'RSAES-PKCS1-V1_5', {
md: forge.md.sha1.create(),
mgf: forge.mgf.mgf1.create(forge.md.sha1.create())
}));
const encryptedPass = forge.util.encode64(
publicKey.encrypt("密码", 'RSAES-PKCS1-V1_5', {
md: forge.md.sha1.create(),
mgf: forge.mgf.mgf1.create(forge.md.sha1.create())
}));
pm.environment.set("username",encryptedUser)
pm.environment.set("password",encryptedPass)
离线环境加密
操作步骤与在线相似。当网络不稳定,或者在局域网使用时,可以先下载离线的forge.js脚本。然后通过http方式发布到本地环境或网络稳定的云服务器上。
不太建议直接将js文本粘贴在变量里,容易造成页面卡死。
不太建议打印res.text(),打开console时容易卡死。
// // if(!pm.environment.has("forgeJS")){
pm.sendRequest("http://qinstyle.cn/forge.js", function (err, res) {
if (err) {
console.log("hellworld")
console.log(err);
} else {
// console.log(res.text())
pm.environment.set("forgeJS", res.text());
}
})
// }
eval(pm.environment.get("forgeJS"));
const pubKey = pm.environment.get("encryptKey");
const publicKey = forge.pki.publicKeyFromPem(pubKey);
const encryptedUser = forge.util.encode64(
publicKey.encrypt("用户名", 'RSAES-PKCS1-V1_5', {
md: forge.md.sha1.create(),
mgf: forge.mgf.mgf1.create(forge.md.sha1.create())
}));
const encryptedPass = forge.util.encode64(
publicKey.encrypt("密码", 'RSAES-PKCS1-V1_5', {
md: forge.md.sha1.create(),
mgf: forge.mgf.mgf1.create(forge.md.sha1.create())
}));
pm.environment.set("username",encryptedUser)
pm.environment.set("password",encryptedPass)
详情请见: