B4J Question Sort json by the keys

Blueforcer

Well-Known Member
Licensed User
Longtime User
I want to do this in B4J:

JavaScript:
const crypto = require('crypto'); // npm install crypto
const _ = require("lodash"); // npm install lodash
const header = { "payloadVersion": 2, "signatureVersion" : 1 };
const APP_SECRET = "a751abdb-e260-4bfd-a42c-60660561123d-3d8e6a30-0f39-42f0-a1ec-e47d47fb1392";

function sortKeys(obj) {
  if(_.isArray(obj)) {
    return obj.map(sortKeys);
  }
  if(_.isObject(obj)) {
    return _.fromPairs(_.keys(obj).sort().map(key => [key, sortKeys(obj[key])]));
  }
  return obj;
}

function getSignature(message, appsecert) {
    return crypto.createHmac('sha256', appsecert).update(message).digest('base64');
}

let payload = {
  "replyToken": "6ec1f778-e92f-487c-9818-bdbe3438f30e",
  "clientId": "alexa-skill",
  "createdAt": 1567852244,
  "deviceId": "5d737888aea17c30a056d759",
  "deviceAttributes": [],
  "type": "request",
  "action": "setPowerState",
  "value": {
     "state": "On"
  }
}

// Sort the json by the keys first
payload = sortKeys(payload);

// Calculate HMAC
const HMAC = getSignature(JSON.stringify(payload), APP_SECRET);
const signature = { "HMAC": HMAC };
const event = { header: header, payload: payload, signature : signature };

console.log(event);


// Output:

/*
{ header: { payloadVersion: 2, signatureVersion: 1 },
  payload:
   { action: 'setPowerState',
     clientId: 'alexa-skill',
     createdAt: 1567852244,
     deviceAttributes: [],
     deviceId: '5d737888aea17c30a056d759',
     replyToken: '6ec1f778-e92f-487c-9818-bdbe3438f30e',
     type: 'request',
     value: { state: 'On' } },
  signature: { HMAC: '5aR5dHuVPOb1rYrWIzSbwqJX6mWMlH1EluQ2Pl7sPDg=' } }
*/

i think ive done the HMAC calculation right with this hint


The payload is a map in my app.

But now im stuck at the part where i need to sort the json after using json generator:
// Sort the json by the keys first

how can i do this?
 

Blueforcer

Well-Known Member
Licensed User
Longtime User
Mhh,
you wrote in the lib comments that this lib doesn't work?
Furthermore it doesn't seem to have a sort option.

In this case it is very important to have the right Json order, otherwise the signiture is not correct.
 
Upvote 0

Blueforcer

Well-Known Member
Licensed User
Longtime User
Youre right, doenst make sense. I ask the developers and they said that the example is wrong :)
Now it works.. thank you anyway
 
Upvote 0
Top