const net = require('net'); var crypto = require('crypto'); function secureSend(options, cmdSend, cb){ const promise = new Promise(function(resolve, reject){ let reqHash = crypto.createHmac('sha256', options.hmacKey); reqHash.setEncoding('binary'); let resHash = Buffer.allocUnsafe(options.hashByteLength); let gotBytes = Buffer.allocUnsafe(options.randDataLength); let gotBytesNum = 0; let res = null; // The final analyzed response var client = new net.Socket(); client.connect(options.port, options.ip, ()=>{ gotBytesNum = 0; if(typeof options.onConnect === 'function') options.onConnect(); client.write('X'); //necessary for the arduino ethernet library }); client.on('error', (err) => { reject(err); }); client.on('close', function() { if(res === null) reject(new Error('Connection closed before the response was sent.')); else resolve(res); }); client.on('data', (data) => { gotBytesNum += data.length; if(gotBytesNum <= options.randDataLength){ reqHash.update(Buffer.from(data), 'binary'); for(i=0; i options.randDataLength){ if (gotBytesNum > (options.randDataLength + options.hashByteLength)) reject(new Error('Server returned more bytes than expeced')); for(i=0; i