1. Home
  2. Explore
  3. Computer Science
  4. Cryptography Fundamentals

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Cryptography Fundamentals

Mastering Cryptography Fundamentals with Node.js Crypto Module

πŸ” Introduction to Cryptography

Cryptography (from Greek kryptos meaning "hidden") is the science of secret communication. It enables two parties to exchange messages over an insecure channel while ensuring that an eavesdropper cannot understand the contents.

In modern online interactions, cryptography is essential for protecting data. Node.js includes a built-in crypto module that provides cryptographic operations, based on OpenSSL. It requires no installation and offers a wide range of algorithms.

The crypto module documentation lists APIs alphabetically, but understanding which algorithm to use requires background knowledge. This guide bridges that gap by explaining fundamental concepts alongside practical Node.js code examples.


πŸ”’ Symmetric Encryption

Symmetric encryption uses a single shared key for both encryption and decryption. Both parties (typically named Alice and Bob) must agree on this key in advance and keep it secret from an eavesdropper (Eve).

Basic Process

  • Plaintext (original message) is passed through a deterministic encryption algorithm together with the key.

  • The output is ciphertext, which appears meaningless.

  • The ciphertext can be sent over an insecure channel.

  • The recipient applies the decryption algorithm using the same key to recover the original plaintext.

Plaintext + Key β†’ Encryption β†’ Ciphertext
Ciphertext + Key β†’ Decryption β†’ Plaintext

Choosing an Algorithm – AES

Node.js provides the getCiphers() function, which returns a list of available cipher algorithms (e.g., 171 on one machine). A widely used standard is the Advanced Encryption Standard (AES). It is implemented across many languages, making cross-platform encryption possible.

  • AES-256-CBC – a specific AES variant:

    • 256 refers to the key size in bits (256 bits). Large key sizes make brute-force attacks infeasible.

    • CBC stands for Cipher Block Chaining, a mode where the plaintext is split into blocks and each block is encrypted sequentially.

Initialization Vector (IV)

In CBC mode, an initialization vector (IV) is required for the first block. The IV is a random value that changes with each encryption. Its purpose:

  • Even if Alice sends the same plaintext ("Hello") every day with the same key, the ciphertext will be different because the IV differs.

  • This prevents pattern analysis attacks (e.g., Eve trying to match ciphertext to known plaintext).

The sender sends the IV, the ciphertext, and optionally the algorithm name. The recipient must use the same IV for decryption.

Implementation in Node.js (Alice – Encryption)

const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const plaintext = Buffer.from('Hello, Bob!', 'utf-8'); // never use plain strings
const iv = crypto.randomBytes(16); // 16 bytes for AES-256-CBC
const key = // ... (discussed later)

const cipher = crypto.createCipheriv(algorithm, key, iv);
let ciphertext = cipher.update(plaintext);
ciphertext = Buffer.concat([ciphertext, cipher.final()]);
// Send iv, ciphertext to Bob

Implementation (Bob – Decryption)

const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(ciphertext);
decrypted = Buffer.concat([decrypted, decipher.final()]);
// decrypted now contains the original plaintext

Both encryption and decryption APIs mirror each other.


πŸ”‘ Key Derivation Functions (KDFs)

Using a human-memorable password directly as the key is dangerous because passwords have low entropy – they come from a small set. Even if users substitute "o" with "0", the search space remains small.

A Key Derivation Function (KDF) solves this by deriving a strong, long key from a weaker input (such as a password).

Purpose of KDFs

  • They are intentionally slow (CPU- and memory-intensive) to make brute-force attempts costly.

  • However, attackers could use precomputed tables (rainbow tables) of common passwords processed through popular KDFs.

The Salt – Preventing Precomputed Attacks

A KDF uses a salt – a random value added to the password before processing. Even if Eve obtains the salt, she must run the expensive KDF for each password guess with that specific salt. This makes precomputed tables useless.

Scrypt, provided by Node.js, is a popular KDF. Others include hkdf and pbkdf2.

Example (Using scrypt)

const key = crypto.scryptSync(password, salt, keyLength);
// password is a string or buffer, salt is random bytes

The salt is generated with crypto.randomBytes() and should be stored alongside the ciphertext (or transmitted with it).


🎲 Generating Randomness

Cryptographic security depends on unpredictable random values. Never use Math.random() – it is not cryptographically secure (predictable under certain conditions).

Node.js crypto provides:

  • crypto.randomBytes(size) – returns a buffer of random bytes.

  • crypto.randomFill(buffer) – fills an existing buffer with random values.

  • crypto.randomInt([min], max) – returns a random integer within a range.

  • crypto.randomUUID() – generates a random UUID (v4).

All are asynchronous (callback-style); use util.promisify to get promises.


πŸ”„ Diffie-Hellman Key Exchange – Solving the Key Distribution Problem

The key distribution problem asks: how can Alice and Bob agree on a shared secret over an insecure channel without ever meeting? The Diffie-Hellman (DH) key exchange (1970s) provides an elegant solution.

How It Works

  1. Alice chooses:

    • A large prime ppp

    • A generator ggg

    • Her private key aaa (random)

    • Computes public key: A=gamod  pA = g^a \mod pA=gamodp

  2. Alice sends (p,g,A)(p, g, A)(p,g,A) to Bob (publicly).

  3. Bob chooses his private key bbb, computes his public key: B=gbmod  pB = g^b \mod pB=gbmodp, and also computes the shared secret: S=Abmod  pS = A^b \mod pS=Abmodp.

  4. Bob sends BBB to Alice.

  5. Alice computes the shared secret: S=Bamod  pS = B^a \mod pS=Bamodp.

Result: Both derive SSS (the same number), but Eve, knowing p,g,A,Bp, g, A, Bp,g,A,B, cannot compute SSS due to the difficulty of the discrete logarithm problem.

Node.js Implementation

// Alice
const alice = crypto.createDiffieHellman(primeLength); // e.g., 2048 bits
const alicePrime = alice.getPrime();
const aliceGenerator = alice.getGenerator();
const alicePublicKey = alice.generateKeys();

// Send alicePrime, aliceGenerator, alicePublicKey to Bob

// Bob
const bob = crypto.createDiffieHellman(alicePrime, aliceGenerator);
const bobPublicKey = bob.generateKeys();
const bobSharedSecret = bob.computeSecret(alicePublicKey);

// Send bobPublicKey to Alice
const aliceSharedSecret = alice.computeSecret(bobPublicKey);
// Both secrets are identical

Note: createDiffieHellman can be slow (e.g., 20 seconds). Elliptic Curve Diffie-Hellman (ECDH) is a faster alternative using elliptic curves, also available in the crypto module.


πŸ›‘οΈ Asymmetric Encryption (RSA)

Diffie-Hellman still requires a key exchange with every new party. RSA (Rivest–Shamir–Adleman) eliminates this: each party has a key pair – a private key (kept secret) and a public key (shared openly).

RSA Encryption

  1. Bob generates his RSA key pair once.

  2. He publishes his public key.

  3. Alice encrypts a message using Bob's public key – only Bob's private key can decrypt it.

This solves the key distribution problem: no prior agreement needed.

Implementation

Key generation (Bob):

const { generateKeyPair } = require('crypto');

generateKeyPair('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: { type: 'spki', format: 'pem' },
  privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
}, (err, publicKey, privateKey) => {
  // Save keys to files
});

Encryption (Alice):

const encrypted = crypto.publicEncrypt(bobsPublicKey, bufferPlaintext);

Decryption (Bob):

const decrypted = crypto.privateDecrypt({
  key: bobsPrivateKey,
  padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
}, encrypted);

Note: RSA is beginning to show its age against quantum computers. For highly sensitive applications, post-quantum cryptography is already being considered (e.g., Apple iMessage).


✍️ Signing and Verifying

Encryption ensures secrecy, but not authenticity. How does Bob know a message truly came from Alice? Digital signatures prove the origin and integrity of a message.

Signing Process

  1. Alice has her private key.

  2. She creates a signature by signing the message with her private key (often combined with a hash function).

  3. She sends the message (possibly unencrypted) and the signature to Bob.

  4. Bob uses Alice's public key to verify the signature.

Only Alice's private key can generate a signature that verifies correctly with her public key.

Node.js Implementation

Signing (Alice):

const signature = crypto.sign('sha256', bufferMessage, alicesPrivateKey);
// Send message and signature to Bob

Verification (Bob):

const isValid = crypto.verify('sha256', bufferMessage, alicesPublicKey, signature);
// Returns true if genuine

HMAC – Symmetric Signing

For symmetric cryptography (same key for both parties), HMAC (Hash-based Message Authentication Code) provides integrity and authenticity. crypto.createHmac('sha256', key).update(message).digest().


πŸ“œ Certificates and the Chain of Trust

Digital signatures alone do not prove who owns a public key – anyone could claim to be Alice. Public key certificates solve this by binding a public key to an identity.

Certificate Structure

A certificate contains:

  • Subject – the identity (e.g., name, organization)

  • Public key – the key being certified

  • Issuer – the entity that issued the certificate

  • Validity period – "valid from" to "valid to"

  • Digital signature – created by the issuer's private key

Certificate Signing Request (CSR)

To obtain a certificate, the subject creates a CSR containing their public key and identity. The issuer (a Certificate Authority, CA) verifies the subject's identity and signs the CSR, producing a signed certificate.

Chain of Trust

To verify Alice's certificate, Bob needs the issuer's public key. That issuer's certificate itself may be signed by a higher authority. This forms a certificate chain ending at a root certificate that is inherently trusted (e.g., embedded in the operating system).

In code, Node.js provides the X509Certificate class:

const cert = new crypto.X509Certificate(pemCert);
cert.subject       // e.g., 'CN=Alice'
cert.issuer        // e.g., 'CN=Carol'
cert.validFrom     // date string
cert.validTo       // date string

Verification of one certificate using another's public key:

const caCert = new crypto.X509Certificate(caPem);
const isVerified = cert.checkIssued(caCert); // true if valid chain

🌐 Real-World Example: EU Digital COVID Certificate

During the pandemic, many countries used QR codes containing a digitally signed JSON payload. The payload included name, vaccine type, and dates – not encrypted, but signed with the Ministry of Health's private key. The public key was publicly available (e.g., on GitHub). Anyone could verify the signature offline, without contacting a server, using standard cryptographic tools.


🧩 Summary of Key Concepts

Concept

Purpose

Node.js Module

Symmetric encryption (AES)

Secrecy with shared key

crypto.createCipheriv / createDecipheriv

Key derivation (scrypt)

Derive strong key from password

crypto.scryptSync

Randomness

Generate unpredictable values

crypto.randomBytes and others

Diffie-Hellman

Establish shared secret over insecure channel

crypto.createDiffieHellman

RSA

Public-key encryption

crypto.generateKeyPair, publicEncrypt/privateDecrypt

Digital signatures

Authenticity and integrity

crypto.sign / crypto.verify

HMAC

Symmetric authentication

crypto.createHmac

Certificates

Bind public key to identity

crypto.X509Certificate


πŸ“š Resources for Further Learning

  • The Code Book by Simon Singh – a history of cryptography from Caesar to modern times.

  • Node.js crypto documentation (online).

  • Web Crypto API for browser environments (similar concepts, different API).

  • All code examples from this talk are available in a public repository with unit tests (ensuring correctness).

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent