Node API Request using AES-ECB Encryption : Fail (The header content contains invalid characters)

205 Views Asked by At

fairly noobish at aes-ecb encryption, apologies in advance.

I am trying to make an API call to a server that requires a encrypted payload. I'm having a little trouble in the sequence in which i encrypt my data converting between base64 and ascii.

When i run the below code, i keep getting

The header content contains invalid characters.

I suspect it may be the way i'm converting the encrypted data between types but not entirely sure. Any thoughts would be really appreciated.

var request = require("request");
var aesjs = require('aes-js');

var apiKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
var privateKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

var method = 'GET';
var url = 'https://apiurl.com';
var agent = "app /1.0 Android/8.1.0 (Android)";

var options = { 
    method: method,
    url: url,
    headers: 
    {   'X-API-KEY': apiKey,
        'X-CSN-USER-AGENT': agent,
        'apiData' : GetAndEncryptApiData(method, url)
    }
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

function GetAndEncryptApiData(method, url){
    var isoTimestamp = new Date().toISOString();;
    var text = `uri:${url} \nmethod:${method}\ntimestamp:${isoTimestamp}`;
    var key = Buffer.from(privateKey, 'base64'); 
    var aesEcb = new aesjs.ModeOfOperation.ecb(key);
    var textToBytes = aesjs.utils.utf8.toBytes(text);
    var paddedData = aesjs.padding.pkcs7.pad(textToBytes);
    var encryptedData = aesEcb.encrypt(paddedData);
    var output = Buffer.from(encryptedData).toString('ascii');

    return output;
}
0

There are 0 best solutions below