crypto module examples in Node.js
The crypto
module in Node.js provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. It allows developers to handle cryptographic operations such as encryption, decryption, hashing, and creating digital signatures. Here’s an overview of the main features and functionalities offered by the crypto
module:
Key Functionalities of the crypto
Module
-
Hashing
Hash functions are used to generate fixed-size outputs (hash values) from arbitrary-sized data. The
crypto
module supports various hash algorithms such as MD5, SHA-256, SHA-512, etc.const crypto = require('crypto'); const hash = crypto.createHash('sha256'); hash.update('Hello, World!'); const hashValue = hash.digest('hex'); console.log('SHA-256 Hash:', hashValue);
-
Encryption and Decryption
The
crypto
module provides interfaces for symmetric and asymmetric encryption. It supports algorithms like AES (Advanced Encryption Standard) for symmetric encryption and RSA (Rivest-Shamir-Adleman) for asymmetric encryption.const crypto = require('crypto'); // Symmetric encryption (AES) const secretKey = crypto.randomBytes(32); // Generate a random key const iv = crypto.randomBytes(16); // Initialization vector const cipher = crypto.createCipheriv('aes-256-cbc', secretKey, iv); let encrypted = cipher.update('Sensitive data', 'utf8', 'hex'); encrypted += cipher.final('hex'); console.log('Encrypted:', encrypted); // Decryption const decipher = crypto.createDecipheriv('aes-256-cbc', secretKey, iv); let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); console.log('Decrypted:', decrypted);
-
Digital Signatures
Digital signatures are used to verify the authenticity and integrity of data. The
crypto
module supports generating and verifying digital signatures using algorithms like RSA.const crypto = require('crypto'); const privateKey = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }).privateKey; const sign = crypto.createSign('RSA-SHA256'); sign.update('Data to be signed'); const signature = sign.sign(privateKey, 'hex'); console.log('Signature:', signature); const verify = crypto.createVerify('RSA-SHA256'); verify.update('Data to be signed'); const isValid = verify.verify(publicKey, signature, 'hex'); console.log('Signature is valid:', isValid);
-
Random Values
The
crypto
module provides methods for generating secure random bytes and random values, which are crucial for creating cryptographic keys, salts, initialization vectors, etc.const crypto = require('crypto'); const randomBytes = crypto.randomBytes(16); console.log('Random Bytes:', randomBytes.toString('hex')); const randomValue = crypto.randomInt(1, 100); console.log('Random Value:', randomValue);
Additional Features
-
Diffie-Hellman Key Exchange: Support for Diffie-Hellman key exchange for secure key establishment in asymmetric encryption.
-
PBKDF2: Password-based key derivation function 2 for securely deriving keys from passwords using HMAC-SHA1, HMAC-SHA256, HMAC-SHA512, etc.
-
TLS/SSL: Integration with Node.js's TLS/SSL API for secure communication over networks.
Use Cases
-
Secure Authentication: Generate and verify passwords securely using hash functions and salt.
-
Data Integrity: Ensure data integrity by creating and verifying digital signatures.
-
Data Encryption: Encrypt sensitive data at rest or during transmission using symmetric or asymmetric encryption algorithms.