In Node.js, the TLS "Transport Layer Security" module provides functionality for creating TLS/SSL (Secure Sockets Layer) encrypted connections.
It allows us to create secure servers and clients for encrypted communication over the network.
Concepts related to TLS/SSL in Node.js using the TLS module:
The "tls.createServer" method is used to create a TLS/SSL server. We need to provide the server's "private key" and "certificate".
The options object passed to "createServer" or "connect" can include various properties, such as "key", "cert", "ca", "requestCert", and "rejectUnauthorized".
These properties control aspects like "server authentication", "client authentication", and "certificate verification".
const tls = require('tls'); const fs = require('fs'); const options = { key: fs.readFileSync('node-server-key.pem'), cert: fs.readFileSync('node-server-cert.pem'), }; const server = tls.createServer(options, (cleartextStream) => { console.log('Client connected via TLS'); cleartextStream.write('Welcome to the secure server!\n'); cleartextStream.pipe(cleartextStream); }); const PORT = 8000; server.listen(PORT, () => { console.log(`TLS Server listening on port ${PORT}`); });
The "tls.connect" method is used to create a TLS/SSL client. We need to provide the server's `hostname` and `port`, as well as the trusted certificate authority's "CA" certificate.
const tls = require('tls'); const fs = require('fs'); const options = { host: 'localhost', port: 8000, ca: [fs.readFileSync('node-client-cert.pem')], }; const client = tls.connect(options, () => { console.log('Client connected via TLS'); client.write('Hello from the TLS client!'); }); client.on('data', (data) => { console.log('Received from server:', data.toString()); }); client.on('end', () => { console.log('Client disconnected'); });
The TLS/SSL server and client objects emit various events, such as 'secureConnection', 'data', 'end', and 'error'. Handling these events is important for managing the TLS connection.
server.on('secureConnection', (cleartextStream) => { console.log('Secure connection established'); }); client.on('error', (err) => { console.error('Client error:', err); });
The examples above use self-signed certificates for simplicity. In a production environment, we would typically use certificates signed by a trusted certificate authority (CA).
Ensure that your Node.js version supports the latest TLS/SSL protocols and ciphers to maintain security.
These examples illustrate the basics of creating TLS/SSL servers and clients using the tls module in Node.js.
When working in a real-world scenario, it's essential to consider security best practices and use certificates from trusted CAs to establish secure connections.