Cryptography in Node.js: Encryption and Hashing with crypto

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Cryptography in Node.js: the crypto module for encryption and hashing



In modern web development, data security is a critical aspect. Node.js provides a built-in crypto module that implements cryptographic functions, including symmetric and asymmetric encryption, hashing, and message authentication codes (HMAC). In this article, we will thoroughly examine the main capabilities of the crypto module with practical examples.



Installation and setup

The crypto module is part of the Node.js standard library, so no additional installation is required. To use it, simply import it:

const crypto = require('crypto');


Data hashing

Hashing is a one-way transformation of data into a fixed-length string. The most popular algorithm is SHA-256. Hashes are used for data integrity verification and password storage (in combination with a salt).



const data = "Secret message";const hash = crypto.createHash('sha256')    .update(data)    .digest('hex');

console.log(`SHA-256 hash: ${hash}`);// Output: 64-character string


To enhance password security, always use a salt and the PBKDF2 or bcrypt algorithm. Example with PBKDF2:



const password = "user_password";const salt = crypto.randomBytes(16).toString('hex');

crypto.pbkdf2(password, salt, 100000, 64, 'sha512', (err, derivedKey) => { if (err) throw err; console.log(`Password hash: ${derivedKey.toString('hex')}`); console.log(`Salt: ${salt}`);});


Symmetric encryption (AES)

Symmetric encryption uses the same key for encryption and decryption. The most common algorithm is AES (Advanced Encryption Standard). Let's look at encryption and decryption using AES-256-CBC.



const algorithm = 'aes-256-cbc';const key = crypto.randomBytes(32); // 256-bit keyconst iv = crypto.randomBytes(16);  // initialization vector

// Encryptionfunction encrypt(text) { const cipher = crypto.createCipheriv(algorithm, key, iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); return { iv: iv.toString('hex'), encryptedData: encrypted };}

// Decryptionfunction decrypt(encryptedData, ivHex) { const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(ivHex, 'hex')); let decrypted = decipher.update(encryptedData, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted;}

// Usage exampleconst message = "Confidential data";const encrypted = encrypt(message);console.log(`Encrypted: ${encrypted.encryptedData}`);

const decrypted = decrypt(encrypted.encryptedData, encrypted.iv);console.log(`Decrypted: ${decrypted}`);


Important: Never use the same IV for different messages. Generate a new random IV for each encryption operation.



Asymmetric encryption (RSA)

Asymmetric encryption uses a key pair: a public key for encryption and a private key for decryption. RSA is the most popular algorithm.



const { generateKeyPairSync, publicEncrypt, privateDecrypt } = crypto;

// Key generationconst { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' }});

// Encryption with public keyconst dataToEncrypt = "Secret message for RSA";const encryptedData = publicEncrypt(publicKey, Buffer.from(dataToEncrypt));console.log(`Encrypted with RSA: ${encryptedData.toString('base64')}`);

// Decryption with private keyconst decryptedData = privateDecrypt(privateKey, encryptedData);co

Recommendations