Postman实现SHA256withRSA签名

@

获取pmlib

引入依赖bundle.js,有以下两种方式:

  1. 从github下载postman collection ,并导入进你的集合里
    官方使用介绍
  2. 所需js全部复制保存成一个全局变量如:pmlib_code
    在这里插入图片描述
  3. 把自己的私钥设置成环境变量如:pri_key
    在这里插入图片描述

使用Pre-request Script对请求进行加签(具体加签字段请看自己项目)

// 使用eval执行js
eval(pm.globals.get('pmlib_code'))

// 生成rfctime
let date = new Date()
let y = date.getFullYear()
let m = date.getMonth()+1<10?'0'+(date.getMonth()+1):(date.getMonth()+1)
let d = date.getDate()<10?'0'+date.getDate():date.getDate()
let hh = date.getHours()<10?'0'+date.getHours():date.getHours();            
let mm = date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes()
let ss = date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds()
this.rfc_time = y +'-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
this.rfc_time = this.rfc_time.replace(/\s+/g, 'T')+'+08:00'
pm.variables.set('rfctime',this.rfc_time)
// console.log(pm.variables.get('rfctime'))

const privkey = pm.environment.get('pri_key').replace(/\\n/g, "\n")

// 随机字符串
const uuid = pm.variables.replaceIn('{{$randomUUID}}')
pm.variables.set('nonce_str', uuid)

const requestBodyRaw = pm.variables.replaceIn(pm.request.body == undefined ? '' : pm.request.body.raw)

const now = pm.variables.replaceIn('{{$timestamp}}')
pm.variables.set('req_time', now)
// 具体加密字段拼接请依据项目情况案例是:method+\n+url+\n+timestamp+\n+nonce_str+\n+body
var dataToSign = pm.request.method + "\n" +
    pm.request.url.getPathWithQuery() + "\n" +
    now + "\n" +
    uuid + "\n" +
    requestBodyRaw

console.log(dataToSign)

const sha256withrsa = new pmlib.rs.KJUR.crypto.Signature({"alg": "SHA256withRSA"});
sha256withrsa.init(privkey);

sha256withrsa.updateString(dataToSign);

const sign = pmlib.rs.hextob64(sha256withrsa.sign());

// console.log(sign);
pm.variables.set('sign', sign)
// 添加请求头
pm.request.headers.add({
    key:"Authorization",
    value:"SHA256-RSA nonce_str={{nonce_str}},timestamp={{req_time}},signature={{sign}}"
});

至此SHA256withRSA签名已完成
在这里插入图片描述

posted @ 2021-07-20 17:38  网名余先生  阅读(1626)  评论(0编辑  收藏  举报