What is the process for converting the output of cryptoJS.sha256 to binary in a Postman pre-request script?

Seeking assistance in creating an HMAC signature using a pre-request script in Postman. While troubleshooting, it has become apparent that there is an issue with the signature generation process. Although a proof of concept example provides expected results, I am struggling to pinpoint the error, particularly in the conversion phase. Upon researching, I came across suggestions on Stack Overflow indicating CryptoJS internally defaults to binary. Therefore, hashing should automatically include necessary conversions. Below is the code attempted in Postman alongside a working implementation in nodeJS.

var CryptoJS = require("crypto-js");

const d = new Date();
const timestamp = d.getTime();
const postData = {};
postData.nonce = 100;  
postman.setEnvironmentVariable('nonce', postData.nonce); 

const secret = CryptoJS.enc.Base64.parse(pm.environment.get("apiSecret"));
const path = pm.globals.get("balanceMethod");
const message =  CryptoJS.SHA256( encodeURI(postData.nonce + postData)) ; // ...

const hmacDigest = CryptoJS.HmacSHA512(path + message, secret);
postman.setEnvironmentVariable('API-Signature', CryptoJS.enc.Base64.stringify(hmacDigest)); 
console.log(CryptoJS.enc.Base64.stringify(hmacDigest));

Does this apply to my situation in that I’d need to convert my sha256 message into a bytes array in order to work?

Reference code for building implementation that does work with nodeJS:

const getMessageSignature = (path, request, secret, nonce) => {
    const message       = qs.stringify(request);
    const secret_buffer = new Buffer(secret, 'base64');
    const hash          = new crypto.createHash('sha256');
    const hmac          = new crypto.createHmac('sha512', secret_buffer);
    const hash_digest   = hash.update(nonce + message).digest('binary');
    const hmac_digest   = hmac.update(path + hash_digest, 'binary').digest('base64');
    return hmac_digest;
};

Same reference code for building implementation in python3:

    req['nonce'] = 100
    postdata = urllib.parse.urlencode(req)

    encoded = (str(req['nonce']) + postdata).encode()
    message = urlpath.encode() + hashlib.sha256(encoded).digest()
    signature = hmac.new(base64.b64decode(self.secret),
                         message, hashlib.sha512)
    sigdigest = base64.b64encode(signature.digest())

The only piece of post data being sent is the Nonce, currently set at 100 for result replication and signature troubleshooting. The Python and nodeJS implementations align with expectations and function correctly.

Answer №1

If you're struggling to migrate from the Crypto library to the Crypto-JS library for binary encoding, I recommend checking out this thread. It really helped me with my issue and could potentially resolve yours as well. The key is breaking the input of the HMAC into two parts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve an array from a JSON object by accessing the corresponding key/value pair using the utility library underscore

I have a dataset in JSON format (as shown below) and I am attempting to use the _.where method to extract specific values from within the dataset. JSON File "data": [{ "singles_ranking": [116], "matches_lost": ["90"], "singles_high_rank": [79 ...

Is there a way to display one of the divs in sequence each time the page is reloaded?

Is there a way to display the divs sequentially when the page is refreshed? For instance, on the initial load, only div 1 should appear, and with each refresh it should cycle through divs 2, 3, 4, and 5 before starting over. Below is an example I'm c ...

Guidelines for accessing a specific object or index from a dropdown list filled with objects stored in an array

Here is a question for beginners. Please be kind. I have created a select field in an HTML component using Angular, populated from an array of objects. My goal is to retrieve the selection using a method. However, I am facing an issue where I cannot use ...

The first time I tried using React-app, I encountered an error that read "[email protected] postinstall"

I've been struggling to set up create-react-app, encountering the same issue repeatedly. I tried uninstalling and reinstalling node.js, but only the package.json and my-app folder were created. No src or other required folders were generated. Termina ...

Using Laravel to retrieve the selected value of a dynamically generated radio button through a for loop in jQuery

In my view, there is a form with dynamically populated radio buttons sourced from the database. The code snippet for this functionality is as follows: <div class="row"> @foreach($status as $s) <div class="col-md-6"> <label class ...

Incorporate a vibrant red circle within a tab of the navigation bar

I'm looking to incorporate a red dot with a number into a messaging tab to indicate new messages. Below is the HTML code: <ul class="nav pw-nav pw-nav--horizontal"> <li class="nav-item"> <a class="nav ...

Loop through the JSON data to generate clickable links in the innerHTML

I've been searching through various resources for a solution to the issue I'm facing. My goal is to iterate through a JSON object and extract all the ids and corresponding dates from each top_worst section. The structure of the JSON data is as fo ...

I'm curious, what is the optimal method for arranging a json object based on an index contained in each of its properties?

I'm working with an array of objects, looking like this myArray = [ { id: 3, data: foo }, { id: 7, data: bar } ] However, I would like to transform it into the following structure transformedArray = { 3: ...

Converting city/country combinations to timezones using Node.js: A comprehensive guide

When provided with the name of a city and country, what is the most reliable method for determining its timezone? ...

Is there a way for me to assign values to my array within each loop when the inner elements vary?

Every time I work on this JavaScript code, I feel like I'm close to finishing it but then encounter another obstacle. My goal is to extract values from different elements such as <input type="text"> and <select>. Here's the code snipp ...

Looking to disable the back button in the browser using next.js?

How can I prevent the browser's back button from working in next.js? // not blocked... Router.onRouteChangeStart = (url) => { return false; }; Does anyone know of a way to disable the browser's back button in next.js? ...

Deploying a static website using Node.JS without relying on any frameworks

I am currently working on deploying static web pages, which include HTML, CSS, and JS files, onto Node.js without utilizing any frameworks such as Express. I started by placing all the necessary webpage files into a public folder and then called the index. ...

How can I prevent an endless loop in jQuery?

Look at the code snippet below: function myFunction(z){ if(z == 1){ $(".cloud").each(function(index, element) { if(!$(this).attr('id')){ $(this).css("left", -20+'%'); $(this).next('a').css ...

The Vue-cli webpack development server refuses to overlook certain selected files

I am attempting to exclude all *.html files so that the webpack devserver does not reload when those files change. Here is what my configuration looks like: const path = require('path'); module.exports = { pages: { index: ...

How can I choose which button to click in selenium if there are multiple buttons on the page with the same name, value, and id?

This particular button actually opens a popup, even though it is located on the same page. ![click here for image description][1] I attempted to interact with the element using the following code: driver.findElement(By.tagName("td")).findElement(By.id( ...

Show the cell data when the checkbox next to it is selected

I have a specific table setup and I am trying to display the content of the table cell if its corresponding checkbox is checked upon clicking a button. For example: If Row2 is checked, an alert box should display Row2 Below is my code snippet, Java ...

no visible text displayed within an input-label field

Currently, I have started working on a multi-step form that is designed to be very simple and clean. However, I am facing an issue where nothing is being displayed when I click on the next arrow. I am puzzled as to why it's not even displaying the te ...

`Inability to Execute Callback Function in JQuery AJAX POST Request`

I've created a simple JavaScript method that sends an AJAX request to a server and is supposed to execute a callback function. However, I'm facing an issue where the specified callback function isn't being executed. Despite this, when I chec ...

An issue arose when attempting to access a Mashape web service with JavaScript

I am attempting to make use of a Mashape API with the help of AJAX and JavaScript. Within my HTML, I have a text area along with a button: <div> <textarea id="message" placeholder="Message"> </textarea> <br><br> ...

Why is AJAX failing to execute PHP file from JavaScript?

The Issue: Hello, I have confirmed that my PHP file is functioning properly. However, the AJAX code connected to my JavaScript function seems to be malfunctioning. Even though the function is triggered, nothing happens as expected. The Script: Check o ...