How to use crypto module in Node.js
Using the crypto module in Node.js provides cryptographic functionality for hashing, encryption, and security operations in server applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented cryptographic operations extensively in authentication systems, data protection, and security-critical applications. From my expertise, the most essential approach is using crypto module methods for password hashing, data encryption, and secure token generation with proper security practices. This built-in module provides production-ready cryptographic operations without requiring external dependencies.
Use the crypto module for secure hashing, encryption, and random data generation in Node.js applications.
const crypto = require('crypto')
// Generate secure random data
function generateSecureToken(length = 32) {
return crypto.randomBytes(length).toString('hex')
}
// Hash data with SHA-256
function hashData(data) {
return crypto.createHash('sha256').update(data).digest('hex')
}
// Hash password with salt (simplified - use bcrypt for production)
function hashPassword(password, salt = null) {
if (!salt) {
salt = crypto.randomBytes(16).toString('hex')
}
const hash = crypto.createHash('sha256').update(password + salt).digest('hex')
return { hash, salt }
}
// Symmetric encryption/decryption
function encrypt(text, key) {
const algorithm = 'aes-256-gcm'
const iv = crypto.randomBytes(16)
const cipher = crypto.createCipher(algorithm, key)
let encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex')
return {
encrypted,
iv: iv.toString('hex')
}
}
function decrypt(encryptedData, key) {
const algorithm = 'aes-256-gcm'
const decipher = crypto.createDecipher(algorithm, key)
let decrypted = decipher.update(encryptedData.encrypted, 'hex', 'utf8')
decrypted += decipher.final('utf8')
return decrypted
}
// Usage examples
console.log('Token:', generateSecureToken())
console.log('Hash:', hashData('Hello World'))
const passwordResult = hashPassword('mypassword')
console.log('Password hash:', passwordResult)
const encrypted = encrypt('sensitive data', 'mySecretKey')
console.log('Encrypted:', encrypted)
console.log('Decrypted:', decrypt(encrypted, 'mySecretKey'))
Here crypto.randomBytes() generates cryptographically secure random data, createHash() provides various hashing algorithms, and createCipher()/createDecipher() handle symmetric encryption. Always use proper key management and consider using established libraries like bcrypt for password hashing in production applications.
Best Practice Note:
This is the same approach we use in CoreUI backend services for API authentication, data protection, and security token generation in enterprise environments. Always use established cryptographic libraries for production password hashing and implement proper key management practices to maintain security standards.



