Node.js
AES
Learn AES encryption with crypto.createCipheriv.
AES encryption
AES (Advanced Encryption Standard) is two-way symmetric encryption. The same key is used for both encryption and decryption. In Node.js you create a cipher with crypto.createCipheriv(algorithm, key, iv).
Example: const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);. Here key must be 32 bytes (256 bits), iv 16 bytes (initialization vector). The iv must differ for each encryption; you generate it with crypto.randomBytes(16). Encryption: cipher.update("text", "utf8", "hex") and cipher.final("hex"). Decryption: crypto.createDecipheriv uses the same key and iv. In AES-CBC mode the ciphertext is a multiple of the block size (16 bytes); PKCS7 padding is applied. The key and iv must be stored or transmitted together safely.
Key and IV
For AES-256-CBC the key must be 32 bytes, the IV 16 bytes. The IV must be unique for each encryption; with the same key and IV the same plaintext gives the same ciphertext. This opens the door to replay attacks.
Example: const key = crypto.randomBytes(32); const iv = crypto.randomBytes(16);. The key is stored long-term in a safe place. The IV is regenerated for each encryption and sent alongside the ciphertext (it need not stay secret). To decrypt, the same IV is needed: crypto.createDecipheriv("aes-256-cbc", key, iv). The key must be a Buffer; randomBytes already returns one. With the wrong key or IV decryption throws.
Exercise Encrypt text with AES
Import with const crypto = require("node:crypto");. Generate key and IV with const key = crypto.randomBytes(32); and const iv = crypto.randomBytes(16);. Create cipher with const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);. Encrypt with let enc = cipher.update("gizli", "utf8", "hex"); enc += cipher.final("hex");. Print with console.log("Ciphertext length: " + enc.length).
Show example solution
const crypto = require("node:crypto");
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
let enc = cipher.update("gizli", "utf8", "hex");
enc += cipher.final("hex");
console.log("Ciphertext length: " + enc.length);
Test yourself
-
Complete the createCipheriv call
const cipher = crypto.____("aes-256-cbc", key, iv);
Show answer
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
-
Which three parameters does createCipheriv take?
crypto.createCipheriv(alg, key, iv)
- algoritma, metin, anahtar
- algoritma, anahtar, IV
- algoritma, IV, metin
- anahtar, IV, metin
Show answer
algoritma, anahtar, IV — It takes algorithm, key, and IV.
-
Match each piece to its role
- createCipheriv
- Creates cipher
- key
- 32-byte key
- iv
- 16-byte init vector
- update/final
- Produces ciphertext
Next lesson: Summary - Crypto