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 β PlaintextChoosing 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 BobImplementation (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 plaintextBoth 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 bytesThe 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
Alice chooses:
A large prime p
A generator g
Her private key a (random)
Computes public key: A=gamodp
Alice sends (p,g,A) to Bob (publicly).
Bob chooses his private key b, computes his public key: B=gbmodp, and also computes the shared secret: S=Abmodp.
Bob sends B to Alice.
Alice computes the shared secret: S=Bamodp.
Result: Both derive S (the same number), but Eve, knowing p,g,A,B, cannot compute S 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 identicalNote: 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
Bob generates his RSA key pair once.
He publishes his public key.
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
Alice has her private key.
She creates a signature by signing the message with her private key (often combined with a hash function).
She sends the message (possibly unencrypted) and the signature to Bob.
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 BobVerification (Bob):
const isValid = crypto.verify('sha256', bufferMessage, alicesPublicKey, signature);
// Returns true if genuineHMAC β 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 stringVerification 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 |
|
Key derivation (scrypt) | Derive strong key from password |
|
Randomness | Generate unpredictable values |
|
Diffie-Hellman | Establish shared secret over insecure channel |
|
RSA | Public-key encryption |
|
Digital signatures | Authenticity and integrity |
|
HMAC | Symmetric authentication |
|
Certificates | Bind public key to identity |
|
π Resources for Further Learning
The Code Book by Simon Singh β a history of cryptography from Caesar to modern times.
Node.js
cryptodocumentation (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.