crypto in nodejs

medium · Node.js — Server-side JavaScript

In Node.js, secure data handling is managed by the built-in Crypto module. While both Hashes and HMACs (Hash-based Message Authentication Codes) are used to transform data into a fixed-length string, they serve different security purposes. 1. Hashes (One-Way Data Fingerprints) A hash is a one-way function that turns an input (like a password or a file) into a fixed-length string. If the input changes by even one character, the resulting hash changes completely (the Avalanche Effect ). One-Way: You cannot reverse a hash to get the original text. Deterministic: The same input always produces the same hash. Common Algorithms: sha256 , sha512 . Code Example: Creating a Hash const crypto = require('crypto'); const data = "Careeroza-Secure-Data"; const hash = crypto.createHash('sha256').update(data).digest('hex'); console.log(hash);  // Output: a 64-character hex string unique to that data 2. HMAC (Keyed Hashing) An HMAC is like a hash, but it requires a Secret Key . It ensures both Integrity (the data hasn't changed) and Authenticity (the person who sent the data knows the secret). Why use it? Standard hashes are vulnerable to "length extension attacks." HMACs prevent this by mixing in a secret key. Common Use Case: Signing JSON Web Tokens (JWTs) or verifying webhooks (like from Stripe or Razorpay). Code Example: Creating an HMAC const crypto = require('crypto'); const secret = 'my-super-secret-key'; const message = 'Important transaction data'; const hmac = crypto.createHmac('sha256', secret)                    .update(message)                    .digest('hex'); console.log(hmac); 3. Key Differences  Feature  Hash  HMAC  Input  Just the Data  Data + Secret Key  Purpose  Data Integrity (Checking for corruption)  Authentication + Integrity  Security  Vulnerable if someone knows the algorithm  Only secure if the key remains secret  Use Case  File checksums, finding duplicate data  API signatures, Webhook verification 4. Hashing Passwords (A Warning) Never use standard createHash for passwords. Because hashes are deterministic and fast, hackers use "Rainbow Tables" (pre-computed lists of hashes) to crack them in seconds. For passwords, you should use Salting and Key Stretching with algorithms like Scrypt, bcrypt or Argon2 . The Better Way (Scrypt): const password = 'user-password-123'; const salt = crypto.randomBytes(16).toString('hex'); crypto.scrypt(password, salt, 64, (err, derivedKey) => {   if (err) throw err;   console.log(derivedKey.toString('hex')); // This is safe to store in a DB }); 5. Summary of the Crypto Workflow Select Algorithm: Choose a strong one (like sha256 ). Initialize: Use createHash or createHmac . Update: Feed the data into the object using .update() . Finalize: Use .digest('hex') to get the final string.

Back to Node.js — Server-side JavaScript

Browse all study material on Careeroza