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 Built-in crypto Module



In modern web development, data security is a critical aspect. Node.js provides a powerful and flexible built-in crypto module that implements a wide range of cryptographic functions. This module does not require installing additional packages and allows you to solve tasks such as hashing, symmetric and asymmetric encryption, creating digital signatures, and HMAC (Hash-based Message Authentication Code).



In this article, we will thoroughly examine the main capabilities of crypto and provide practical code examples.



Main Capabilities of the crypto Module



  • Hashing — converting data of arbitrary length into a fixed-length string (SHA-256, SHA-512, MD5).
  • Symmetric encryption — encryption and decryption with a single secret key (AES-256-CBC, AES-192-GCM).
  • Asymmetric encryption — encryption with a key pair (public/private) based on RSA or ECDH.
  • HMAC — hashing with a secret key to verify message integrity and authenticity.
  • Digital signatures — creating and verifying signatures to confirm authorship.


Importing the Module



The crypto module is built into Node.js, so it is imported in the standard way:



const crypto = require('crypto');


Example 1: Data Hashing (SHA-256)



Hashing is a one-way function often used for storing passwords and verifying file integrity.



const data = 'PythonLib — educational portal';

// Create a SHA-256 hashconst hash = crypto.createHash('sha256');hash.update(data);const hexHash = hash.digest('hex');

console.log('Original data:', data);console.log('SHA-256 hash:', hexHash);// Output: SHA-256 hash: b5a1... (64 characters)


Important: For storing passwords, do not use a simple hash, but a function with a "salt" — for example, crypto.scryptSync() or pbkdf2Sync().



Example 2: Password Hashing with Salt (scrypt)



const password = 'MySecurePassword123';

// Generate a random saltconst salt = crypto.randomBytes(16).toString('hex');

// Create a hash with salt (scrypt)const hash = crypto.scryptSync(password, salt, 64).toString('hex');

console.log('Salt:', salt);console.log('Password hash:', hash);

// To verify, use the same salt and compare hashesconst isMatch = crypto.scryptSync(password, salt, 64).toString('hex') === hash;console.log('Password matches:', isMatch); // true


Example 3: Symmetric Encryption AES-256-CBC



Symmetric encryption uses one key for both encryption and decryption. The AES-256-CBC algorithm also requires an initialization vector (IV).



// Encryption functionfunction encrypt(text, key) {    const iv = crypto.randomBytes(16); // Generate IV    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);    let encrypted = cipher.update(text, 'utf8', 'hex');    encrypted += cipher.final('hex');    return { iv: iv.toString('hex'), encrypted };}

// Decryption functionfunction decrypt(encrypted, key, ivHex) { const iv = Buffer.from(ivHex, 'hex'); const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted;}

// Usageconst key = crypto.randomBytes(32); // 256-bit keyconst secretMessage = 'Secret data for PythonLib';

const encryptedData = encrypt(secretMessage, key);console.log('Encrypted:', encryptedData.encrypted);console.log('IV:', encryptedData.iv);

const decryptedMessage = decrypt(encryptedDa

Recommendations