Creating HMAC BodyHash Sha256 nodejs

Issue

I am trying to integrate with a service (paysera https://developers.paysera.com/) that uses HMAC Authentication. I’ve manage to integrate every GET endpoint. Nevertheless, when it comes to the POST request it seems the code is not working.

createHMACAuth(data) {
    let bodyHash = crypto.createHash('sha256').update(JSON.stringify(data)).digest('base64');
    let method = 'POST';
    let path = `/rest/v1/transfers`;
    let ts = moment().unix();
    let nonce = GUID(32);
    let port = 443;
    let macString = `${ts}\n${nonce}\n${method}\n${path}\n${host}\n${port}\n${bodyHash || ''}\n`;
    let my_mac_key = 'my_mac_key';
    let my_mac_id = 'my_mac_id';
    let mac = crypto.createHmac('sha256', my_mac_key).update(macString).digest('base64');
    let headerString = `MAC id="${my_mac_id}", ts="${ts}", nonce="${nonce}", mac="${mac}", ext="body_hash=${bodyHash}"`;
    return  headerString;
  }
  
  let data = {
    key: 'value',
    otherkey: 'othervalue'
  };
  let headers = {
      Host: 'wallet.paysera.com',
      'User-Agent': `Paysera node.js library`,
      mac_id: 'my_mac_id',
      Authorization: createHMACAuth(data);
   };

   POST_REQUEST(`${headers.host}/rest/v1/transfers`, data, headers, (err, res) => console.log(res))

The response I get is:

{ 
  error: 'unauthorized',
  error_description: 'Given MAC content body hash does not match actual hash of content' 
}

Any help will be much appreciated!

Solution

I had an error when generating the body_hash

Fix

  createHMACAuth(method, path, data) {
    let bodyHash, ext;
    if (method === 'POST') {
      ext = `body_hash=${encodeURIComponent(this.createHash(JSON.stringify(data)))}`;
    }
    this.method = method;
    this.path = `/${path}`;
    let nonce = `${U.GUID(32)}`;
    let port = 443;
    let macString = `${this.ts}\n${nonce}\n${this.method}\n${this.path}\n${this.host}\n${port}\n${ext || ''}\n`;
    let mac = this.createHMACHash(macString);
    let headerString = `MAC id="${this.mac_id}", ts="${this.ts}", nonce="${nonce}", mac="${mac}"`;
    if (method === 'POST') headerString += `, ext="${ext}"`
    return  headerString;
  }

Answered By – ferpalma21.eth

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.