Example Code: Verify Password Hashes
Below are practical examples showing how to verify
Argon2id and PBKDF2 password hashes in popular backend
languages.
Node.js Examples
Verify Argon2id Hash (Node.js)
// Install dependency
// npm install argon2
const argon2 = require('argon2');
async function verifyArgon2(password, encodedHash) {
try {
return await argon2.verify(encodedHash, password);
} catch (err) {
return false;
}
}
// Example usage
const match = await verifyArgon2(
'mySecretPassword',
'$argon2id$v=19$m=65536,t=3,p=1$0II7M4P/ppkK1emcdMUTOg$Z2gF3BTRJKMQfOzQfVCl7xOG+2r57qsUDN1oPVV/kgM'
);
console.log(match);
Argon2 hashes are self-contained. Parameters and salt
are extracted automatically during verification.
Verify PBKDF2 Hash (Node.js)
const crypto = require('crypto');
function verifyPBKDF2(password, salt, iterations, keyLength, hashAlgo, derivedKeyBase64) {
const derivedKey = crypto.pbkdf2Sync(
password,
salt,
iterations,
keyLength / 8,
hashAlgo.toLowerCase()
);
return crypto.timingSafeEqual(
derivedKey,
Buffer.from(derivedKeyBase64, 'base64')
);
}
// Example usage
const match = verifyPBKDF2(
'mySecretPassword',
'mySaltValue',
100000,
256,
'SHA256',
'Base64DerivedKeyHere'
);
console.log(match);
PHP Examples
Verify Argon2id Hash (PHP)
<?php
$password = 'mySecretPassword';
$hash = '$argon2id$v=19$m=65536,t=3,p=1$0II7M4P/ppkK1emcdMUTOg$Z2gF3BTRJKMQfOzQfVCl7xOG+2r57qsUDN1oPVV/kgM';
if (password_verify($password, $hash)) {
echo 'Password matches';
} else {
echo 'Password does not match';
}
PHP natively supports Argon2id via password_verify().
Verify PBKDF2 Hash (PHP)
<?php
function verifyPBKDF2($password, $salt, $iterations, $keyLength, $algo, $derivedKeyBase64) {
$derivedKey = hash_pbkdf2(
$algo,
$password,
$salt,
$iterations,
$keyLength / 4,
true
);
return hash_equals(
$derivedKey,
base64_decode($derivedKeyBase64)
);
}
// Example usage
$match = verifyPBKDF2(
'mySecretPassword',
'mySaltValue',
100000,
256,
'sha256',
'Base64DerivedKeyHere'
);
echo $match ? 'Password matches' : 'Password does not match';
Verification Rules
- Argon2 hashes can be verified directly using the encoded hash.
- PBKDF2 verification requires the same salt, iterations, hash algorithm, and key length.
- Always use timing-safe comparisons for hash verification.