Search code examples
javascriptnode.jssecurityencryptionserver-to-server

Node.js server-to-server encryption


I want to make a Node.js daemon that runs on multiple computers and is able to exchange messages between the different daemons. Of course the communication should be encrypted, but I really don't know what kind of encryption I should use for server-to-server encryption. The protocol I'm using right now is TCP via net.createServer. How should I encrypt the communication assuming I have a already exchanged password on both devices? How do I make it secure to the most known attacks?

Edit: Is using RSA combined with an "authentication password" secure? This password would then be submitted with every request, the whole message (including the password) would be encrypted with the RSA public key (which can be downloaded without encryption).


Solution

  • I think the right way to do this is to communicate via ssl, see here:

    http://nodejs.org/docs/v0.4.2/api/tls.html

    You could also do a quick and dirty encryption using the crypto module:

    var crypto = require('crypto'); 
    var algorithm = 'aes256'; // or any other algorithm supported by OpenSSL
    
    exports.encryptString = function(text) {
    
    var cipher = crypto.createCipher(algorithm, key);
    return cipher.update(text, 'utf8', 'hex') + cipher.final('hex');
    
    };
    
    var key = "123456"; 
    
    exports.decryptString = function(text) {
    
    var decipher =  crypto.createDecipher(algorithm, key);
    return decipher.update(text, 'hex', 'utf8') + decipher.final('utf8');
    
    };
    

    Both servers need the public key.

    You'll probably want to use JSON stringify and parse functions on top of the above (I had those lying around). You could do it in middleware that deciphers incoming requests and ciphers outgoing ones.