What Is Bcrypt and Why Use It?
Bcrypt is a password-hashing algorithm created in 1999 by Niels Provos and David Mazieres. Unlike fast hash functions such as MD5 or SHA-256, bcrypt is deliberately slow, making brute-force attacks computationally expensive. It automatically generates and embeds a random salt into the hash output, protecting against precomputed rainbow table attacks. The resulting hash string contains the algorithm version, cost factor, salt, and hash in a single portable format.
Understanding the Cost Factor
The cost factor is an integer between 4 and 31 that controls the number of key expansion rounds as a power of 2. A cost of 10 performs 1024 rounds, while a cost of 12 performs 4096 rounds. As computing power increases over time, you can raise the cost factor to maintain security without changing your hashing infrastructure. The OWASP Foundation recommends a minimum cost factor of 10, with 12 being a good balance between security and user experience for most web applications.
Bcrypt Hash Format Explained
A bcrypt hash string looks like $2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy. The first segment ($2a$) identifies the bcrypt version. The second segment ($10$) is the cost factor. The next 22 characters are the base64-encoded salt, and the remaining 31 characters are the base64-encoded hash. This self-contained format means you never need to store the salt separately; it is embedded directly in the hash string.
Best Practices for Password Hashing
Always hash passwords on the server side in production systems, never on the client. Use a cost factor of at least 10, and benchmark your server to find the highest cost factor that keeps login time under one second. Never store plaintext passwords, even temporarily. When users change their password, generate a completely new hash rather than updating the existing one. Consider migrating to Argon2id for new projects if your platform supports it, as it adds memory-hardness resistance.





