Hashing password plays crucial role on security of systems and networks. So in this post we'll learn how to hash passwords before saving it on database using Node.js. For this we need a authentication library named auth-verify
npm install auth-verify
Making the configuration
For hashing the password we should make correct configuration:
const AuthVerify = require('auth-verify');
const auth = new AuthVerfiy({
hashAlg: 'pbkdf2', // or 'scrypt'
iterations: 100000,
keyLen: 64
});
π hashAlg: 'pbkdf2'
This chooses the hashing algorithm.
pbkdf2
- Stands for Password-Based Key Derivation Function 2
- Built into Node.js crypto
- Designed specifically for passwords
-
Uses:
- password
- salt
- iterations (many rounds)
- βοΈ Secure
βοΈ Battle-tested
βοΈ Slower on purpose (good against brute-force)
scrypt (alternative)
- Even more memory-hard
- Stronger against GPU attacks
- Slightly heavier on the server
π Rule of thumb:
-
pbkdf2β safe, standard, widely used -
scryptβ stronger, modern, more expensive
π iterations: 100000
This is how many times the hash function runs.
Think of it like this:
Instead of hashing once, hash 100,000 times
Why?
- Makes attacks VERY slow
- If an attacker tries millions of passwords β π CPU melts Example:
- 1 iteration β β οΈ weak
- 10,000 β okay
100,000 β good (production-level)
βοΈ More iterations = more security
β Too many = slower login
π 100_000 is a great balance
π keyLen: 64
This is the length of the final hash (in bytes).
-
64 bytes= 512 bits - Longer hash = harder to crack
- Stored in DB as hex/base64
Example:
password β pbkdf2 β 64-byte hash
- βοΈ 32 bytes β ok
- βοΈ 64 bytes β strong
Hashing the password
auth.crypto.hash("myPassword123", (err, result)=> {
if(err) console.log(err);
console.log(result);
});
Verifying the password
auth.crypto.verify("secret123", result, (err, valid)=> {
if(err) console.log(err);
console.log(valid) // true
});
Full example
const AuthVerify = require('auth-verify');
const auth = new AuthVerfiy({
hashAlg: 'pbkdf2', // or 'scrypt'
iterations: 100000,
keyLen: 64
});
auth.crypto.hash("myPassword123", (err, result)=> {
if(err) console.log(err);
console.log(result);
auth.crypto.verify("secret123", result, (err, valid)=> {
if(err) console.log(err);
console.log(valid) // false
});
});
Top comments (2)
When you use "secret123" to verify the hashed result, how does the initial hashing command know that that secret will be used for verifying? Does the initial command not need to know the secret as well?
The hash doesnβt need to know the password in advance β during verification, the entered password is hashed again with the same salt and configuration, and the two hashes are compared.