Node.js7 min read

Crypto and Hashing

Hash passwords, encrypt data, and generate secure tokens.

Michael Torres
December 19, 2025
0.0k0

Crypto and Security

Node.js has built-in crypto module for security operations.

Hashing with SHA-256

const crypto = require('crypto');

const hash = crypto.createHash('sha256');
hash.update('my secret data');
const digest = hash.digest('hex');

console.log(digest);

Output: a1b2c3d4e5f6... (64 character hex string)

Password Hashing with bcrypt

npm install bcrypt
const bcrypt = require('bcrypt');

async function hashPassword(password) {
  const saltRounds = 10;
  const hash = await bcrypt.hash(password, saltRounds);
  return hash;
}

async function verifyPassword(password, hash) {
  const match = await bcrypt.compare(password, hash);
  return match;
}

const hashed = await hashPassword('myPassword123');
console.log(hashed);

const isValid = await verifyPassword('myPassword123', hashed);
console.log(isValid);

Output:

$2b$10$N9qo8uLOickgx2ZMRZoMye...
true

Generate Random Tokens

const crypto = require('crypto');

const token = crypto.randomBytes(32).toString('hex');
console.log(token);

const { randomUUID } = require('crypto');
const id = randomUUID();
console.log(id);

Output:

a1b2c3d4e5f6...
a1b2c3d4-e5f6-7890-abcd-ef1234567890

Real Example: Password Reset Token

const crypto = require('crypto');

function generateResetToken() {
  const token = crypto.randomBytes(32).toString('hex');
  
  const hash = crypto
    .createHash('sha256')
    .update(token)
    .digest('hex');
  
  return {
    token,
    hash
  };
}

const { token, hash } = generateResetToken();

console.log('Send to user:', token);
console.log('Store in DB:', hash);

HMAC for Message Authentication

const crypto = require('crypto');

const secret = 'my-secret-key';
const message = 'important data';

const hmac = crypto.createHmac('sha256', secret);
hmac.update(message);
const signature = hmac.digest('hex');

console.log(signature);

Use HMAC to verify data hasn't been tampered with.

Encryption and Decryption

const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

function encrypt(text) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

function decrypt(encrypted) {
  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

const encrypted = encrypt('secret message');
console.log('Encrypted:', encrypted);

const decrypted = decrypt(encrypted);
console.log('Decrypted:', decrypted);

Real Example: User Registration

const express = require('express');
const bcrypt = require('bcrypt');
const app = express();

app.use(express.json());

app.post('/register', async (req, res) => {
  const { email, password } = req.body;
  
  const hashedPassword = await bcrypt.hash(password, 10);
  
  await User.create({
    email,
    password: hashedPassword
  });
  
  res.json({ message: 'User created' });
});

app.post('/login', async (req, res) => {
  const { email, password } = req.body;
  
  const user = await User.findOne({ email });
  
  if (!user) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }
  
  const isValid = await bcrypt.compare(password, user.password);
  
  if (!isValid) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }
  
  res.json({ message: 'Logged in' });
});

app.listen(3000);

Key Takeaway

Use bcrypt for passwords, never plain hashing. Generate secure tokens with randomBytes. HMAC for message authentication. Store encryption keys securely, never in code.

#Node.js#Crypto#Security#Hashing