CryptoJS does not work in pre-request script

Simple script:
const​ hash = CryptoJS.HmacSHA256(‘message’, ‘secret’);
console.log(‘hash:’ + hash);

What I see from console is:
SyntaxError: Invalid or unexpected token

Version 7.25.2 for Linux

What should I do to make it work?

Hey @rvitalik34

Welcome to the Postman community!! :trophy:

I did get the same error message when I copied your snippet, might be just the forum syntax weirdness.

I went over to the documentation and copied the same encryption method line from here:

That seemed to work for me, could you give it a go please?

When you copy-paste examples from CryptoJS website then you copiend invisible characters also(zero width whitespace) They generate parsing errors which you mentioned: SyntaxError: Invalid or unexpected token. To solve this just type code manually. Or search for editor when you can view all non-printable characters and remove them.

I do agree that sometimes the examples didn’t work as expected may be copy/paste issue. You can find examples related to Crypto JS now on Postman collection.

Just fork it and use it directly.

Run in Postman

Reference for HMAC example : Postman

Cheers.

I got it to work with this :slightly_smiling_face:

var CryptoJS = require(“crypto-js”);

// Set your secret key and data to be hashed
var secretKey = “YOUR_SECRET_KEY”;
var data = “YOUR_DATA_TO_BE_HASHED”;

// Generate the hash using HMAC-SHA256 and encode to Base64
var hash = CryptoJS.HmacSHA256(data, secretKey).toString(CryptoJS.enc.Base64);

// Set the hash as a header
pm.request.headers.add({
key: “Authorization”,
value: "Bearer " + hash
});

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