Random & TLS

randomBytes & TLS

In Node.js, security is built on the foundation of randomness and secure transport layers. Both are handled by the crypto and tls modules.

1. Randomness (The crypto module)


Computers are deterministic, so creating "true" randomness is difficult. Node.js provides two ways to generate random data:

CSPRNG (Cryptographically Secure Pseudo-Random Number Generator)

For security tasks (like generating salts, session IDs, or tokens), you must use crypto.randomBytes(). This pulls entropy from the operating system.


const crypto = require('crypto');

// Generate 16 bytes of random data (128-bit)
crypto.randomBytes(16, (err, buffer) => {
  if (err) throw err;
  console.log(buffer.toString('hex')); // e.g., 'f3a2c1...'
});


randomInt
If you need a random number within a range for security purposes (like a 6-digit OTP), use crypto.randomInt().

const otp = crypto.randomInt(100000, 999999);
console.log(`Your OTP is: ${otp}`);


2. TLS (Transport Layer Security)


The tls module provides an implementation of the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols. It is built on top of the net module and is the foundation for https.

How TLS Works (The Handshake)

Before any data is sent, the client and server perform a "Handshake" to:

  1. Agree on the version of TLS to use.

  2. Select the encryption algorithms (Cipher Suites).

  3. Authenticate the identity of the server using a Certificate.

  4. Generate Session Keys for symmetric encryption.


Creating a TLS Server

To run a TLS server, you need a Private Key and a Certificate (usually a .pem or .crt file).

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

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),
};

const server = tls.createServer(options, (socket) => {
  console.log('Client connected', socket.authorized ? 'authorized' : 'unauthorized');
  socket.write('Welcome to the secure server!\n');
  socket.setEncoding('utf8');
  socket.pipe(socket); // Echo server
});

server.listen(8000, () => {
  console.log('TLS server bound on port 8000');
});


3. Key Concepts in TLS\


A. Certificates and CAs

  • Private Key: Stays on the server. Never share it.

  • Certificate: Contains the server's public key and identity.

  • CA (Certificate Authority): A trusted third party (like Let's Encrypt) that signs your certificate to prove you are who you say you are.


B. ALPN (Application-Layer Protocol Negotiation)

This allows the TLS connection to negotiate which protocol to use after the secure link is established (e.g., deciding between HTTP/1.1 and HTTP/2).


C. Perfect Forward Secrecy (PFS)

A feature where even if the server's long-term private key is stolen in the future, past recorded conversations cannot be decrypted. Node.js enables this by default using modern Diffie-Hellman algorithms.


4. Why use tls instead of https?


  • HTTPS: Specifically for web traffic (Port 443).

  • TLS: A general-purpose wrapper. You would use the tls module if you were building a secure Chat Server (TCP), a secure Database Protocol, or a custom IoT communication system that isn't strictly "web-based."