How to use CryptoJS package in Postman Flows Evaluate block

How can we use evaluate block in postman flows to validate the hmac signed payload. I’m using the below code

const crypto = require('crypto'); 
const secret = 'mySecretKey'; 
const payload = request.body; 
console.log(payload);
const receivedHmac = payload;
const data = JSON.stringify(payload); 
const generatedHmac = crypto.createHmac('sha256', secret).update(data).digest('hex');
if (receivedHmac === generatedHmac) { 
    console.log('Payload is valid'); 
    } else {
         console.log('Payload is not valid'); 
    }

This is throwing me an error invalid redefinition of global identifier.

“data” is a reserved variable, so I would change that to something else.

Hi @avionics-specialist3

We support the web crypto API in the evaluate block.

Try the below code:

const secret = 'mySecretKey';
const payload = request.body; 
console.log(payload);
const receivedHmac = 'expected_hmac_here'; 

const encoder = new TextEncoder();
const data = encoder.encode(payload)
  crypto.subtle.importKey('raw', new TextEncoder().encode(secret), {
    name: 'HMAC',
    hash: 'SHA-256',
  }, false, ['sign'])
    .then((key) => crypto.subtle.sign('HMAC', key, data))
    .then((signature) => {
      const generatedHmac = Array.from(new Uint8Array(signature)).map(byte => byte.toString(16).padStart(2, '0')).join('');
      return generatedHmac === receivedHmac;
    })
    .catch((error) => {return error});

If you want a constant time comparison function to compare the HMACs, you can use this function:

function constantTimeCompare(str1: string, str2: string): boolean {
    if (str1.length !== str2.length) {
        return false;
    }

    let result = 0;
    for (let i = 0; i < str1.length; i++) {
        result |= str1.charCodeAt(i) ^ str2.charCodeAt(i);
    }

    return result === 0;
}
constantTimeCompare(receivedHmac, generatedHmac)

The error you’re receiving in your code is in reference to trying to import the crypto library.

1 Like