Using Node.js Crypto Module for Hashing, HMAC, and Symmetric Encryption
This article introduces Node.js's built‑in crypto module, explaining how to perform one‑way hashing with SHA‑256, create HMACs for stronger integrity checks, and use symmetric cipher/decipher for encrypting and decrypting data, complete with practical code snippets.
In the era of the Internet, frequent personal data leaks make data security essential, and Node.js provides the built‑in crypto module for encryption tasks.
Hash algorithms transform input data into a fixed‑size binary value; the process is irreversible, making hashes suitable for login verification. MD5 and SHA‑1 are discouraged due to known vulnerabilities, while SHA‑256 is recommended.
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update('some data to hash');
console.log(hash.digest('hex'));HMAC works like a hash but also incorporates a secret key, providing stronger security.
const crypto = require('crypto');
const hash = crypto.createHmac('sha256', 'a secret');
hash.update('some data to hash');
console.log(hash.digest('hex'));Cipher and Decipher enable reversible encryption. The example uses the AES‑192 algorithm with a password to encrypt clear‑text data and then decrypt it.
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
var encrypted = cipher.update('some clear text data', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted); const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
var decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);These common hashing, HMAC, and symmetric encryption techniques satisfy many Node.js data‑security needs, though higher‑security domains such as banking may require additional mechanisms like digital signatures, verification, or Diffie‑Hellman.
System Architect Go
Programming, architecture, application development, message queues, middleware, databases, containerization, big data, image processing, machine learning, AI, personal growth.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.