chat-client/rsa.js

110 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-04-09 19:18:47 +10:00
if (process.send) {
process.send(JSON.stringify({mode:"hello"}));
}
// Include some libraries
const atob = require("atob");
const btoa = require("btoa");
const node_rsa = require("node-rsa");
const fs = require("fs");
// Load the settings
var settings = require("./settings");
// Some varibles
var rsa_key;
function load_rsa_key()
{
// Is the rsa key not loaded
if(!rsa_key)
{
// Is the rsa key in memory only
if(settings.rsa.in_memory)
{
// Make a new key
rsa_key = new node_rsa({b:settings.rsa.size});
}
else
{
try
{
// Try reading the keys from a file
rsa_key.importKey(fs.readFileSync(settings.rsa.file.public, "utf-8"), "public");
rsa_key.importKey(fs.readFileSync(settings.rsa.file.private, "utf-8"), "private");
}
catch(e)
{
// Load the new rsa key
rsa_key = new node_rsa({b:settings.rsa.size});
// Export the files
fs.writeFileSync(settings.rsa.file.public, rsa_key.exportKey("public"));
fs.writeFileSync(settings.rsa.file.private, rsa_key.exportKey("private"));
}
}
}
}
function callback(data)
{
// Stringify the data
var string = JSON.stringify(data);
// Send it to the parent
process.send(string);
}
process.on('message', function(message)
{
// Decode the message from json
var args = JSON.parse(message);
// Does the parent want to decrypt some data
if(args['mode'] == 'decrypt')
{
// Decrypt the data with the RSA key
console.log(args['data']);
var data = rsa_key.decrypt(args['data'], 'utf-8');
// Send the data back
callback({
mode: "decrypt",
out: btoa(data)
})
}
// Does the parent want the rsa keys
if(args['mode'] == 'get')
{
// Send back the public/private keys
callback({
mode: "get",
public: rsa_key.exportKey("public"),
private: rsa_key.exportKey("private")
});
}
// Does the parent want the rsa key loaded
if(args['mode'] == 'load')
{
// Load the rsa key
load_rsa_key();
// Send confirmation callback
callback({
mode: "load"
})
}
// Does the parent want to kill the task
/*if(args['mode'] == 'kill')
{
// Kill the task
process.exit();
}*/
});