How to establish SSL/TSL socket connection with Nodejs

Asked

Viewed 211 times

0

I created a very simple server socket with Nodejs (V8.11.3) and it is working OK apparently. My goal is to keep an open socket connection continuously with an electronic device (Iot).

QUESTION: How to make communication secure, i.e., how to make a socket SSL/TLS communication with socket? OBS.: I also created a self-signed certificate for testing.

The test socket server (without security) is this below. As I have no experience with Nodejs I imagine there are much better ways...

const net = require('net')

net.createServer(socket => {
    socket.on('error', (err) => {
        console.log('Socket Error: ')
        console.log(err.stack)
    })

    socket.on('data', function(data){
        msg = ''
        msg = data.toString();
        socket.write(msg)
        console.log(msg)
    })
}).listen(8001)

1 answer

0


/*
    DOCUMENTAÇÃO DE REFERÊNCIA:
    https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
    https://nodejs.org/api/tls.html#tls_tls_connect_options_callback

    Este exemplo foi criado com base em um certificado auto-assinado e  
    devem ser alterados os paths dos arquivos, indicando a pasta correta.
*/

const tls = require('tls');
const fs = require('fs');

const options = {
    //key: fs.readFileSync('server-key.pem'),
    key: fs.readFileSync('utils/51952868_localhost.key'),
    //cert: fs.readFileSync('server-cert.pem'),
    cert: fs.readFileSync('utils/51952868_localhost.cert'),

    // This is necessary only if using client certificate authentication.
    //requestCert: true,

    // This is necessary only if the client uses a self-signed certificate.
    //ca: [ fs.readFileSync('client-cert.pem') ]
};

const server = tls.createServer(options, (socket) => {
    console.log('Cliente ' + socket.remoteAddress + ':' + socket.remotePort);

    socket.write('Welcome from Server!\n');

    // Trata a recepção dos dados enviados pelo Cliente
    socket.on('data', function(data){
        msg = ''
        msg = data.toString();
        socket.write(msg)
        console.log(msg)
    })

    // Trata o evento de DESCONEXÃO do Cliente corrente
    socket.on('end', () => {
        console.log('Desconectado!') 
    })

    // Trata todas as condições de ERRO do sistema
    socket.on('error', (err) => {
        console.log('Socket Error: ')
        console.log(err.stack)
    })

});

// Inicia o servidor usando a porta "443" (escolha do usuário)
server.listen(443, () => {
    console.log('Servidor em execução!');
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.