如何在Postman预请求脚本中将cryptoJS.sha256输出设置为二进制

时间:2018-07-09 23:30:40

标签: javascript cryptography postman hmac

我正在尝试使用预请求脚本在邮递员中创建HMAC签名。无需过多介绍实现细节,

我已经确认我生成签名的方法被弄乱了。通过概念验证示例,我可以看到预期的结果,但是我在某处缺少某些内容,无法确定它是否在转换中。我从SO that binary is the default provided by cryptojs internally的其他问题中了解到,简单地调用哈希值就等于要求摘要为您完成转换。这是我尝试在邮递员中运行的代码,以及在nodeJS中显示的有效实现代码。

var CryptoJS = require("crypto-js");

const d = new Date();
const timestamp = d.getTime();
const postData = {};
postData.nonce = 100;  //timestamp * 1000; //nanosecond
postman.setEnvironmentVariable('nonce', postData.nonce); 

const secret = CryptoJS.enc.Base64.parse(pm.environment.get("apiSecret"));
const path = pm.globals.get("balanceMethod");
const message =  CryptoJS.SHA256( encodeURI(postData.nonce + postData)) ; // ...

const hmacDigest = CryptoJS.HmacSHA512(path + message, secret);
postman.setEnvironmentVariable('API-Signature', CryptoJS.enc.Base64.stringify(hmacDigest)); 
console.log(CryptoJS.enc.Base64.stringify(hmacDigest));

Does this apply to my situation in that I’d need to convert my sha256 message into a bytes array in order to work?

用于构建可与nodeJS一起使用的实现的参考代码:

const getMessageSignature = (path, request, secret, nonce) => {
    const message       = qs.stringify(request);
    const secret_buffer = new Buffer(secret, 'base64');
    const hash          = new crypto.createHash('sha256');
    const hmac          = new crypto.createHmac('sha512', secret_buffer);
    const hash_digest   = hash.update(nonce + message).digest('binary');
    const hmac_digest   = hmac.update(path + hash_digest, 'binary').digest('base64');
    return hmac_digest;
};

用于在python3中构建实现的相同参考代码:

    req['nonce'] = 100 #int(1000*time.time())
    postdata = urllib.parse.urlencode(req)

    # Unicode-objects must be encoded before hashing
    encoded = (str(req['nonce']) + postdata).encode()
    message = urlpath.encode() + hashlib.sha256(encoded).digest()
    signature = hmac.new(base64.b64decode(self.secret),
                         message, hashlib.sha512)
    sigdigest = base64.b64encode(signature.digest())

我当前发送的唯一帖子数据是Nonce,我将其故意设置为100,以便能够复制结果以修复生成的签名。似乎关闭,但结果不匹配。 python和nodeJS确实符合预期结果,并且可以正常工作。

1 个答案:

答案 0 :(得分:0)

this线程中查看答案。它帮助我解决了我的问题,也可能是您的情况正在发生的事情。只需将HMAC的输入分为两部分即可。