Skip to main content

Cryptographic Hashing Example

Secure password hashing, data integrity, and verification.

Password Hashing

import crypto from 'crypto'

function hashPassword(password) {
const salt = crypto.randomBytes(16).toString('hex')
const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex')
return { salt, hash }
}

function verifyPassword(password, salt, hash) {
const testHash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex')
return testHash === hash
}

export default async function handler(req, res) {
const { action, password, salt, hash } = req.body

if (action === 'hash') {
if (!password) return res.status(400).json({ error: 'Password required' })
const result = hashPassword(password)
return res.json({ success: true, salt: result.salt, hash: result.hash })
}

if (action === 'verify') {
if (!password || !salt || !hash) return res.status(400).json({ error: 'password, salt and hash required' })
return res.json({ success: true, valid: verifyPassword(password, salt, hash) })
}

res.status(400).json({ error: 'Unknown action' })
}