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'm an "old" programmer who has been blogging for almost 20 years now. In 2017, I started Highline Solutions, a consulting company that helps with software architecture and full-stack development. I have two degrees from Carnegie Mellon University, one practical (Information and Decision Systems) and one not so much (Philosophy - thesis here). Pittsburgh, PA is my home where I live with my wife and 3 energetic boys.
I recently released a web app called TechRez, a "better resume for tech". The idea is that instead of sending out the same-old static PDF resume that's jam packed with buzz words and spans multiple pages, you can create a TechRez, which is modern, visual, and interactive. Try it out for free!
Got a Comment?
Comments (1)
January 31, 2023
Thank you for the example