How to Generate a BCrypt Hash for Testing Login Flows
Testing authentication flows requires test users with valid password hashes. Generating a BCrypt hash manually lets you create seed data, test login with known passwords, and verify auth logic without going through the full registration flow every time.
What BCrypt is
BCrypt is an adaptive hashing algorithm designed specifically for passwords. Unlike general-purpose hashes (SHA-256, MD5), BCrypt is intentionally slow — slow enough that brute-forcing a stolen password database takes years rather than days. The slowness is configurable via the cost factor.
A BCrypt hash looks like this:
$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LdeFcMnFYuXLZQKtG
Breaking this down: $2b$ is the algorithm version, 12 is the cost factor (2^12 = 4096 iterations), and the rest is the salt and hash combined.
Choosing the cost factor
The cost factor (also called work factor or rounds) controls how long hashing takes. BCrypt doubles in computation time with each increment:
- Cost 10: ~100ms per hash (minimum for production in 2024)
- Cost 12: ~400ms per hash (reasonable for most applications)
- Cost 14: ~1.6 seconds per hash (appropriate for high-security contexts)
For testing seed data, cost 10 or 12 is standard — it matches what you'd use in production, so your test hashes are valid against production code.
Using BCrypt hashes in seed data
The typical test setup: generate a BCrypt hash for a known test password (testpassword123), insert it directly into the database as the password hash for a test user, then log in with that password in tests.
# Python — generating a hash for seed data
import bcrypt
password = b"testpassword123"
salt = bcrypt.gensalt(rounds=12)
hashed = bcrypt.hashpw(password, salt)
# Insert hashed.decode() into the database
# Node.js
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash('testpassword123', 12);
// Insert hash into the database
A browser-based BCrypt generator does the same thing without writing code — useful for quickly generating a hash for a seed file or a one-off test account.
Verifying a hash works
After generating a hash and inserting it into a test database, verify it works by attempting a login with the test password. If the login succeeds, the hash is correct. If it fails, check that the hash was stored as a string (not bytes), that the encoding is correct (UTF-8), and that the column length is at least 60 characters (BCrypt hashes are 60 characters).