Hash Payload in Postman with CryptoJS

May 27th 2020

Recently, I created a REST endpoint (webhook) to be hit by a 3rd party. To secure it, I took this basic approach, such that the client would hash the payload (using a supplied secret key) and then put that hashed value in an HTTP header. Upon receiving the request, my endpoint would then do the same, and evaluate whether the hash value passed in the header was equal to the hash value generated on the server.

This all worked great, but testing was a bit of a pain. At first, I was generating the hashed value programmatically and then copy-pasting into Postman. Ugh. Then I figured out that with a few minutes of effort I could do this using pre-request scripts and CryptoJS (which seems to be imported by default by Postman).

The script was just this:

var requestBody = pm.request.body.toString();
var secret = postman.getEnvironmentVariable("secret")
var bytes = CryptoJS.HmacSHA256(pm.request.body.toString(), secret);
var hash = bytes.toString(CryptoJS.enc.Hex).toUpperCase();

console.log('X-FooBar-Signature: ' + hash);

postman.setEnvironmentVariable("hashValue", hash);

So now before each request this code automatically generates the hash value and plugs it directly into the header value using the Postman environment variable.

Hope that helps someone!

I believe that software development is fundamentally about making decisions, and so this is what I write about (mostly). In 2018 I started Highline Solutions, a consulting practice that helps companies with architecture, devops, and full-stack development. I have two degrees from Carnegie Mellon University, one in Information and Decision Systems and one in Philosophy (thesis). I live in Pittsburgh, PA with my wife and 3 energetic boys.
Got a Comment?

Comments (0)

 None so far!