Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 133 ยท Security and Cryptography

Encryption: AES, RSA and Keys

Learn Node.js encryption with the crypto module - AES-256-GCM authenticated encryption, nonces, key derivation, RSA and Ed25519 key pairs, signatures and the Web Crypto subtle API.

Encryption turns readable data (the plaintext) into unreadable data (the ciphertext) using a secret called a key. Only someone with the right key can turn it back. You reach for it when you store a secret in a database, send data over a channel you do not fully trust, or need to prove that a message really came from you.

Node.js ships a complete cryptography toolkit in the node:crypto module, backed by OpenSSL. The hard part is not calling the functions. The hard part is choosing the right primitive and using it without the subtle mistakes that break security: reusing a nonce, forgetting authentication, hard-coding a key. This lesson teaches the three tools you will actually use: symmetric encryption (AES-GCM), key derivation (turning a password into a key), and asymmetric cryptography (RSA and Ed25519 key pairs, encryption and signatures). If you have not met hashes yet, read Hashing and HMAC first, and Randomness and Identifiers explains where good keys and nonces come from.

Never invent your own cryptographic scheme and never use a fixed key or nonce in real code. The examples in this lesson use fixed values only so that the output is repeatable on every run. In production, keys come from a secret store (see Configuration, Secrets and Environment) and nonces are fresh random bytes.

Symmetric versus asymmetric

There are two families, and they solve different problems.

  • Symmetric encryption uses one key to lock and unlock. It is fast and perfect for data at rest (files, database columns) or for two parties who already share a secret. The problem is sharing that key safely.
  • Asymmetric (public-key) cryptography uses a pair: a public key you can hand to anyone and a private key you never share. Anyone can encrypt to your public key or verify your signature; only you can decrypt or sign. It is slower and limited in message size, so in practice it protects a small thing (a symmetric key, a hash) rather than bulk data.

Real systems such as TLS combine both: public-key cryptography agrees on a key, then fast symmetric encryption protects the traffic.

AES-256-GCM: authenticated encryption

The best default for symmetric encryption is AES in GCM mode with a 256-bit key. GCM is an authenticated mode: besides scrambling the data, it produces a short authentication tag (16 bytes). When you decrypt, the tag proves that nobody changed the ciphertext. Older modes such as AES-CBC encrypt without authenticating, which lets attackers flip bits or probe your decryption code. Prefer GCM (or ChaCha20-Poly1305) and you skip a whole class of bugs.

Three inputs matter:

Input Size Rule
Key 32 bytes for AES-256 Secret, random or derived, never hard-coded
IV / nonce 12 bytes for GCM Unique for every message under one key
Tag 16 bytes Produced by encryption, required for decryption

The example below uses a fixed key and nonce purely to make the output repeatable.

Node.js Encrypt and decrypt with AES-256-GCM

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Step by step: createCipheriv builds an encryptor from the algorithm name, key and IV. update feeds data in (you can call it many times for streaming input) and final flushes the last block. Only after final can you call getAuthTag. For decryption you must call setAuthTag before final, and final is where the tag is checked.

Tampering is detected

What happens if an attacker flips one bit of the ciphertext? Because the tag no longer matches, final() throws instead of handing you garbage.

Node.js Modified ciphertext is rejected (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The thrown message is Unsupported state or unable to authenticate data. It is not very friendly, but it is exactly what you want: wrap decryption in try/catch, treat any failure as "this data is not trustworthy", and never reveal why it failed to an outside caller (detailed error messages can help attackers). Handling thrown errors well is covered in Errors and Error Handling.

The nonce rule

GCM's security collapses if you encrypt two different messages with the same key and the same IV. An attacker who sees both ciphertexts can combine them and cancel out the secret keystream, leaking the relationship between the plaintexts. You can see the problem with a few lines of XOR.

Node.js Why reusing a nonce is catastrophic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If one of the plaintexts is ever known or guessable, the other falls out. The fix is simple: generate a fresh random 12-byte IV for every message with randomBytes(12) and store it next to the ciphertext. The IV is not secret, only unique.

A practical envelope format

A common pattern packs everything needed for decryption into one value: iv (12) + tag (16) + ciphertext. Here the random IV makes ciphertext differ on every run, so the example prints only stable facts.

Node.js A complete seal and open helper with random IVs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For more on the Buffer slicing used here, see Buffers and Text and Encodings.

Turning a password into a key

An AES key must be 32 random-looking bytes. A human password is neither. A key derivation function (KDF) stretches a password and a salt into a key of the right size, deliberately slowly so that guessing is expensive. Node offers scrypt, pbkdf2 and hkdf.

  • scrypt and pbkdf2 are for passwords: low-entropy secrets that need slow hashing.
  • hkdf is for key material that is already random (a master key, a shared secret) when you need several independent subkeys from it; it is fast because there is nothing to brute-force.
Node.js Derive keys with scrypt, pbkdf2 and hkdf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Salting and comparing derived values for logins is the subject of Passwords, scrypt and Tokens. The key idea for encryption: store the salt and the KDF parameters next to the ciphertext, derive the key when needed, and never store the key itself.

Asymmetric keys: RSA and Ed25519

generateKeyPairSync(type, options) creates a public/private pair. Node wraps the keys in KeyObject values, so you rarely need to touch the text format. When you do need to store or send them, export them as PEM text (readable, base64 with header lines) or DER.

Two algorithms cover almost every need:

  • RSA (2048 bits or more) can encrypt small messages and sign. It is universally supported.
  • Ed25519 is a modern signature algorithm with small keys, fast operations and few ways to misuse it. For signatures only, prefer it when both sides support it.

Encrypting with RSA

RSA can only encrypt a message smaller than the key, minus padding overhead (for a 2048-bit key with OAEP-SHA-256 that is about 190 bytes). So you use it for small secrets, typically a fresh AES key, which then encrypts the real data. This combination is called hybrid encryption.

Node.js Hybrid encryption: RSA protects an AES key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Always set OAEP padding explicitly, as above. Older PKCS#1 v1.5 padding for encryption has known attacks, and Node has disabled it in recent releases for privateDecrypt unless you opt in.

Digital signatures

A signature proves two things: the message was not altered, and it was produced by the owner of the private key. You sign with the private key and verify with the public key. Ed25519 uses the one-shot sign and verify functions (pass null as the algorithm, since the hash is built in).

Node.js Sign and verify with Ed25519 and RSA

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Signatures are the foundation of signed software updates, JWTs signed with RS256 or EdDSA, and webhook verification. Shared-secret alternatives (HMAC) are simpler when both sides trust each other; use signatures when the verifier must not be able to forge messages.

Key exchange: Diffie-Hellman and ECDH

Everything so far assumed both sides already hold the key. How do two programs that have never met agree on a key over a network where an eavesdropper hears every message? Diffie-Hellman (DH) does it with a neat trick. Each side creates a private number and a matching public value. They swap the public values in the open, and each side combines its own private number with the other side's public value. Both calculations arrive at the same shared secret, but an eavesdropper who only saw the public values cannot compute it.

Node offers two flavours:

  • ECDH (elliptic-curve Diffie-Hellman) uses points on a curve. Keys are short and fast, so it is the modern choice. createECDH(curve) is the classic API, and crypto.diffieHellman({ privateKey, publicKey }) works with ordinary KeyObjects such as x25519.
  • Classic DH (createDiffieHellman, getDiffieHellman('modp14')) uses large prime numbers. It still appears in older protocols.

crypto.getCurves() lists the curve names OpenSSL provides (prime256v1, also known as P-256, secp384r1, secp256k1, ...).

Node.js ECDH, X25519 and classic DH

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice four things. First, both sides get identical secrets without ever sending them. Second, the raw secret is not a good key by itself: pass it through a key derivation function such as HKDF (shown earlier in this lesson) with a context string, and use the output as an AES-GCM key. Third, plain Diffie-Hellman has no idea who is on the other end, so an attacker in the middle can run one exchange with each side. Real protocols (TLS, Signal, SSH) authenticate the public values with certificates or signatures. Fourth, for forward secrecy create a fresh key pair for every session and throw it away afterwards; then a later leak of a long-term key cannot decrypt old traffic.

Prefer x25519 through generateKeyPairSync and crypto.diffieHellman in new code, and choose a named group when you need classic DH. Do not generate your own prime with createDiffieHellman(2048) in a request handler: finding a safe prime takes seconds.

The Web Crypto API

Node implements the standard crypto.subtle interface from browsers, available as globalThis.crypto. Its API is promise-based and works with Uint8Array and CryptoKey objects, which makes the same code run in Node, Deno and browsers. Keys can be marked non-extractable so their bytes can never be read back by your own code.

Node.js AES-GCM with crypto.subtle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

node:crypto and Web Crypto are interchangeable for most tasks. Use node:crypto when you want streaming, PEM handling or the widest algorithm list; use crypto.subtle for code you want to share with the browser.

Pitfalls professionals avoid

  • Hard-coded keys and nonces. The demos did it; production code never does. A key in source control is a key published to everyone with repository access.
  • Encrypting without authenticating. Use GCM or ChaCha20-Poly1305. If you must use a non-authenticated mode, add an HMAC and verify it first.
  • Comparing secrets with ===. Use crypto.timingSafeEqual for MACs and tokens to avoid timing leaks.
  • Treating a password as a key. Always run a password through scrypt or pbkdf2 with a random salt.
  • Rolling your own protocol. If a vetted format exists (TLS, JWE, age, libsodium's secretbox), use it. Encryption code is easy to write and very hard to get right.
  • Forgetting key rotation. Store a key version beside each ciphertext so you can introduce a new key and still read old data.
  • Losing the key. There is no backdoor. Encrypted data without its key is gone; back up keys separately from the data they protect.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is AES-256-GCM preferred over unauthenticated modes such as AES-CBC?

    GCM is authenticated encryption: decipher.final() throws if the ciphertext or tag was altered. CBC alone offers no such guarantee.
  2. 2. What is the most dangerous mistake when using AES-GCM?

    Reusing a nonce under one key breaks GCM's confidentiality and lets attackers learn about the plaintexts. The IV is not secret, but it must be unique per message.
  3. 3. You have a human-typed password and need an AES key. What should you do?

    A KDF stretches the password into a proper key and makes brute-force guessing slow. Store the salt (not the key) with the ciphertext.
  4. 4. Why does hybrid encryption wrap a random AES key with RSA instead of encrypting the whole message with RSA?

    RSA messages are limited to a little less than the key size and RSA is slow. AES encrypts the large payload; RSA only protects the small key.
  5. 5. Which key do you use to create a digital signature, and which to verify it?

    Only the owner of the private key can sign, while anyone with the public key can verify, which is why signatures prove who produced a message.

Summary

  • Symmetric encryption (AES) is fast and uses one key; asymmetric cryptography (RSA, Ed25519) uses a public/private pair and is used for key exchange, small secrets and signatures.
  • Use authenticated encryption: aes-256-gcm with a 32-byte key, a unique 12-byte IV per message and a 16-byte tag checked by decipher.final().
  • Never reuse a nonce under the same key and never hard-code keys; store the IV and tag with the ciphertext, not the key.
  • Derive keys from passwords with scrypt or pbkdf2 and a random salt; use hkdf to split already-strong key material into subkeys.
  • generateKeyPairSync creates RSA or Ed25519 keys; use OAEP padding for RSA encryption and sign/verify for signatures.
  • crypto.subtle offers the same ideas through the standard Web Crypto API, shared with browsers.

Next: Passwords, scrypt and Tokens