Bcrypt Explained: Implementing Secure User Authentication in Web Development

Sourav S
3 min readMar 18, 2024

--

Introduction

Bcrypt is a password hashing function designed by Niels Provos and David Mazières. It incorporates a salt to protect against rainbow table attacks and is adaptive over time as it can be made slower as computers get faster.

Why Bcrypt?

In the world of data security, storing user passwords in plain text is a cardinal sin. Passwords should always be hashed, providing a way to verify a password without storing the exact value. Bcrypt is a strong, slow password-hashing algorithm ensuring long crack times on breached databases.

How Does Bcrypt Work?

Bcrypt uses the Blowfish cipher to encrypt a password. It starts by initiating a state using both the password and a salt. Then, it uses a key setup phase, followed by a large number of encryption rounds.

Bcrypt in Action: Usage Examples

In Node.js, you can use npm (Node Package Manager) to install bcrypt. Open your terminal and run the following command in your project directory:

npm install bcrypt

Here are some examples of how to use bcrypt:

const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 'my_password';

bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB.
});

Practical Use Case: Signup Function

Each time a password is hashed, a new salt is generated. This means that even if two users have the same password, their hashed passwords will be different due to the unique salts.

Here’s an example of a signup function in Node.js using bcrypt for password hashing :

const express = require('express');
const bcrypt = require('bcrypt');
const Users = require('./models/Users'); // Assuming you have a Users model

const router = express.Router();

router.post('/signup', async (req, res) => {
try {
const { username, password } = req.body;
const saltRounds = 10;

// Hash the password with a new salt
const hashedPassword = await bcrypt.hash(password, saltRounds);

// Create a new user
const newUser = new Users({
username,
password: hashedPassword,
});

// Save the new user
await newUser.save();

res.status(201).json({ message: 'User created successfully' });
} catch (error) {
res.status(500).json({ error: 'Error creating user' });
}
});

module.exports = router;

Verifying Passwords

After implementing the signup function, the next step is to verify the user’s password during login. This is where bcrypt’s compare function comes into play. It takes the plain text password, hashes it with the stored salt, and then compares it with the stored hash.

Here’s an example of a password verification function in Node.js:

router.post('/login', async (req, res) => {
try {
const { username, password } = req.body;

// Find the user by username
const user = await Users.findOne({ username });

if (!user) {
return res.status(400).json({ error: 'Invalid username or password' });
}

// Compare the provided password with the stored hash
const match = await bcrypt.compare(password, user.password);

if (!match) {
return res.status(400).json({ error: 'Invalid username or password' });
}

res.status(200).json({ message: 'Login successful' });
} catch (error) {
res.status(500).json({ error: 'Error logging in' });
}
});

This function works as follows:

  1. It takes a username and password from the request body.
  2. It finds the user in the database using the provided username.
  3. If the user doesn’t exist, it sends a 400 status code with an error message.
  4. If the user exists, it compares the provided password with the stored hashed password using bcrypt’s compare function.
  5. If the passwords don’t match, it sends a 400 status code with an error message.
  6. If the passwords match, it sends a 200 status code with a success message.

This function ensures that even if an attacker has your user’s hashed password, they won’t be able to log in without the original password. This is because bcrypt’s compare function will always return false for a password that wasn’t hashed with the original salt.

npm link: https://www.npmjs.com/package/bcrypt

Conclusion

Bcrypt is a powerful tool for password hashing. Its ability to generate a unique salt for each password hash makes it a robust choice for securing user passwords. Remember, in the realm of data security, it’s always better to be safe than sorry.

If you found this post valuable, consider following for more insightful content. Your support is appreciated! 😊

--

--

No responses yet