Files

24 lines
677 B
JavaScript
Raw Permalink Normal View History

const crypto = require('crypto')
const PREFIX = 'scrypt$'
function hash(plain) {
const salt = crypto.randomBytes(16).toString('hex')
const digest = crypto.scryptSync(String(plain), salt, 32).toString('hex')
return `${PREFIX}${salt}$${digest}`
}
function isHashed(stored) {
return typeof stored === 'string' && stored.startsWith(PREFIX)
}
function verify(plain, stored) {
if (!isHashed(stored)) return false
const parts = stored.split('$')
const expected = Buffer.from(parts[2], 'hex')
const actual = crypto.scryptSync(String(plain), parts[1], expected.length)
return crypto.timingSafeEqual(expected, actual)
}
module.exports = { hash, verify, isHashed }