HMAC Signature Prescript generated bad signature

I am using a prescript to generate an HMAC signature of the request body, all works find except when the body is empty.

Every other tool I have tried generated the same signature of my development environment, but post man comes up with a different signature.

My PreScript is
pm.variables.set(“hmac”, CryptoJS.HmacSHA256(request.data,pm.environment.get(“SigningKey”)).toString(CryptoJS.digest));

And my SigningKey is
ed2eea4451174aeb9161e0cc1fdf304d4982b18497a6e2842ee3f27ea0948d28

My Backend Code, and Hash and HMAC calculator both say that an emtpy string should produce a signature of
4405dcf4c8c19bb6dbc68573046ff7410057638b2d9e823c095fd758fb5fcd0a

But the script gives me
25a1f4d0f752b515e3c390c4a447887ec6d3371d12f5824225b14b864634398e

I found a few post that seemed to indicate I needed to use a variable for the empty string so I tried this script
x = ‘’
pm.variables.set(“hmac”, CryptoJS.HmacSHA256(x,pm.environment.get(“SigningKey”)).toString(CryptoJS.digest));

But I still get the same incorrect signature.

Any suggestions?

FYI, the script works correctly as long as there is some data in the body, my issue is just the emtpy string, I haven’t figure out any method on my backend trying null, empty string 0 byte etc. to generate the signature that postman is on an empty string

Hi @flight-observer-1467

I think your issue here is that ‘request.data’ will return { } brackets when the payload is blank … so technically this is not an ‘empty’ payload.

Try changing the payload in the CryptoJS.HmacSHA256 function to a blank variable.

const payload = ``;
const secretKey = 'ed2eea4451174aeb9161e0cc1fdf304d4982b18497a6e2842ee3f27ea0948d28';

let hmac = CryptoJS.HmacSHA256(payload,secretKey).toString(CryptoJS.digest);

console.log(hmac);

If this works, you could build a conditional statement to pass in the payload or set it to empty.

something like this:

let payload;

if(JSON.stringify(request.data) === "{}") {
    payload = ``;
} else {
    payload = request.data
}

const secretKey = 'ed2eea4451174aeb9161e0cc1fdf304d4982b18497a6e2842ee3f27ea0948d28';

let hmac = CryptoJS.HmacSHA256(payload,secretKey).toString(CryptoJS.digest);

console.log(hmac);

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.