From 3d7450bfea970c1875ff513acf949cfcb1be15aa Mon Sep 17 00:00:00 2001 From: kasdimos Date: Thu, 21 Nov 2019 16:11:03 +0000 Subject: [PATCH] Upload files to '' --- app.js | 41 +++++++++++++++ secureSendClient.js | 118 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+) create mode 100644 app.js create mode 100644 secureSendClient.js diff --git a/app.js b/app.js new file mode 100644 index 0000000..447fb1e --- /dev/null +++ b/app.js @@ -0,0 +1,41 @@ + +const secureSend = require('./secureSendClient.js'); + +const options = { + hmacKey: 'supersecure', + hashByteLength: 32, + randDataLength: 100, + port: 777, + ip: '192.168.0.6', + + onConnect: () => { + console.log('Connected'); + } +} + +const cmds = { + getGateState:{ + cmd: 0, + responses: [0x00, 0x01, 0x02] /* 0: Closed 1: Open 2: Middle */ + }, + switchGate: { + cmd: 1, + responses: [0x00] /* 0: Cmd received */ + }, + switchLight: { + cmd: 2, + responses: [0x00, 0x01] /* 0: now closed 1: now Open */ + } +}; + +secureSend(options, cmds.switchGate) + .then(res => { + console.log('The response ->'); + console.log(res); + }) + .catch(err => { + console.log('Catched Error ->'); + console.log(err); + }); + +setTimeout(()=>{},6000); \ No newline at end of file diff --git a/secureSendClient.js b/secureSendClient.js new file mode 100644 index 0000000..a85363b --- /dev/null +++ b/secureSendClient.js @@ -0,0 +1,118 @@ + +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