// Get some libraries const net = require("net"); const node_rsa = require("node-rsa"); const bsplit = require("buffer-split"); // Load the settings var settings = require("./settings.json"); // Encryption varibles var encryption; var rsa_key; // Create a client var client = new net.Socket(); function string_decrypt(key, string) { // Convert the string to a buffer var buff = new Buffer.from(string); // Create some new data var decrypted = new Buffer.alloc(buff.length); // Iterate over the string for(var i=0;i= key.str.length) { // Set to zero key.at.rx = 0; } } // Return the encrypted data return decrypted; } function string_encrypt(key, string) { // Convert the string to a buffer var buff = new Buffer.from(string); // Create some new data var encrypted = new Buffer.alloc(buff.length); // Iterate over the string for(var i=0;i 255) e -= 256; encrypted[i] = e; // Add 1 to the key counter key.at.tx += 1; // Is the key counter out of range if(key.at.tx >= key.str.length) { // Set to zero key.at.tx = 0; } } // Return the encrypted data return encrypted; } function make_encryption_key(string) { // Make a new key var key = new Object(); // Set the varibles key.str = string; key.at = new Object(); key.at.rx = 0; key.at.tx = 0; // Return the key return key; } function socket_write(socket, encryption, data) { // Send the data encrypted with JSON socket.write(string_encrypt(encryption, JSON.stringify(data)+"\n")); } function socket_ondata(socket, callback) { // Wait for a response socket.on('data', function(data) { // Decode the data data = JSON.parse(data); // Call the callback callback(data); }); } // Connect to the server client.connect(22068, '127.0.0.1', function() { // Create an rsa key rsa_key = new node_rsa({b:settings.rsa_size}); // Send the public key to the server client.write(rsa_key.exportKey("public")); }); // Set new var sock_new = 2; // Set a temporary encryption varible var raw_encryption_data = ""; var raw_encryption_data_upto = 0; var raw_encryption_data_size = 0; // Wait for data client.on('data', function(data) { if(sock_new == 2) { console.log("Recieved key."); // Set the size of the key raw_encryption_data_size = parseInt(data); // Set sock new to 1 sock_new = 1; } // Is the socket recieving the key else if(sock_new == 1) { console.log(data); // Decode the data raw_encryption_data += data; raw_encryption_data_upto += data.length; console.log(data.length); // Is this the end of the stream if(raw_encryption_data_upto == raw_encryption_data_size) { // Set sock new to 0 sock_new = 0; // Set the key encryption = make_encryption_key(rsa_key.decrypt(raw_encryption_data)); console.log("Done."); socket_write(client, encryption, {message: "hello, world!", number: 53}); } } else { // Decrypt the data data = string_decrypt(encryption, data); // Split the data by newlines data = bsplit(data, Buffer.from("\n")); // Iterate over them for(var i=0;i