Skip to content

Learn online at your pace

Cloud & Security • November 29, 2026 • 8 min read

How to Store Passwords Safely: Hashing, Salting and bcrypt Explained

The Qtec Mastery

Author

How to Store Passwords Safely: Hashing, Salting and bcrypt Explained

If your app has a login page, you are responsible for every password your users trust you with. Many people reuse the same password for email, M-Pesa-linked apps and social media, so a leak from your small school portal can hurt them far beyond your site. This guide to password hashing is for PHP and Laravel developers: you will learn why plain text and encryption are wrong, how bcrypt and Argon2 work, and the exact code to store and check passwords safely.

Never store passwords as plain text or with reversible encryption. Store a slow, salted password hash made with bcrypt or Argon2. In PHP, use password_hash() to create it and password_verify() to check it at login.

Why should you never store passwords in plain text?

A plain-text password column means anyone who sees the database sees every password. That includes an attacker who exploits a bug such as SQL injection, someone who finds a leaked backup, or a staff member who should not have access.

Because so many people reuse passwords, attackers try leaked email and password pairs on other sites. This is called credential stuffing. Your leak becomes your users' problem on email, banking and social apps.

The goal of password storage is simple: even if your entire database is stolen, the attacker should not be able to recover the passwords in any practical way.

What is the difference between hashing and encryption?

Both scramble data, but they are built for different jobs.

EncryptionHashing
Reversible?Yes, with the keyNo, it is one-way
Needs a secret key?YesNo
Good forData you must read again, such as ID numbersPasswords, which you only need to check
If the server is breachedThe key is often stolen tooAttacker must guess each password

You never need to know a user's actual password. You only need to know whether what they type at login matches what they set. Hashing gives you exactly that: you hash the login attempt and compare it with the stored hash.

Encryption is the wrong tool because it can be undone. The encryption key usually lives on the same server, so a serious breach often exposes both the encrypted passwords and the key to unlock them.

What is a salt and why does it matter?

A salt is a random value added to each password before hashing. Every user gets a different salt, and it is stored alongside the hash.

Without salts, two users with the password Nairobi2026 would have identical hashes. An attacker could spot shared passwords instantly and use precomputed tables of hashes for common passwords. With a unique salt, the same password produces a different hash for every user, so each one must be attacked separately.

The good news: modern password functions create and store the salt for you. You should not generate salts yourself.

Why are MD5, SHA-1 and SHA-256 wrong for passwords?

MD5, SHA-1 and SHA-256 are general-purpose hash functions. They were designed to be fast, which is great for checking that a file downloaded correctly and terrible for passwords.

A fast hash lets an attacker with a stolen database and a graphics card try an enormous number of guesses every second. Short and common passwords fall quickly. MD5 and SHA-1 also have known weaknesses that make them unsuitable for any security use today.

Password hashing functions are deliberately slow and tunable. A single login takes a fraction of a second, which your users will not notice, but making billions of guesses becomes very expensive.

What are bcrypt and Argon2?

  • bcrypt has been the standard choice for many years. It has a cost setting: each increase of 1 doubles the work. It only uses the first 72 bytes of a password, which is rarely a problem in practice.
  • Argon2id is a newer design that is also memory-hard, meaning each guess needs a chunk of memory as well as time. This makes large-scale guessing with specialised hardware harder. It is the current first recommendation of many security guides.

Both are good choices. What matters most is that you use one of them through a well-tested library and never write your own.

How do I hash passwords in PHP?

Create the users table

Store the hash in a VARCHAR(255) column. A bcrypt hash is 60 characters today, but Argon2 hashes are longer and PHP's default algorithm may change in future, so give it room:

CREATE TABLE users (
  user_id INT AUTO_INCREMENT PRIMARY KEY,
  student_id INT,
  email VARCHAR(255) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (student_id) REFERENCES students(student_id)
);

Hash the password when a user registers

<?php
$hash = password_hash($password, PASSWORD_DEFAULT);

$stmt = $pdo->prepare(
    'INSERT INTO users (student_id, email, password_hash) VALUES (?, ?, ?)'
);
$stmt->execute([$studentId, $email, $hash]);

PASSWORD_DEFAULT currently uses bcrypt. The result looks like $2y$12$ followed by 53 more characters (older PHP versions before 8.4 default to cost 10, so you may see $2y$10$): 2y is the algorithm, 12 is the cost, and the rest holds the salt and the hash. Everything needed to verify the password is in that one string. If your PHP build supports it, you can use PASSWORD_ARGON2ID instead.

Check the password at login, and rehash if needed

<?php
$stmt = $pdo->prepare('SELECT user_id, password_hash FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user && password_verify($password, $user['password_hash'])) {
    // Upgrade old hashes when the algorithm or cost changes
    if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
        $newHash = password_hash($password, PASSWORD_DEFAULT);
        $update = $pdo->prepare('UPDATE users SET password_hash = ? WHERE user_id = ?');
        $update->execute([$newHash, $user['user_id']]);
    }

    session_regenerate_id(true);
    $_SESSION['user_id'] = $user['user_id'];
} else {
    $error = 'Incorrect email or password.';
}

Three details are worth noticing:

  • password_verify() reads the algorithm, cost and salt from the stored hash, so you never handle the salt yourself.
  • password_needs_rehash() lets you raise the cost or switch algorithms later. Each user is upgraded silently the next time they log in, because that is the only moment you have their plain password.
  • The error message does not say whether the email or the password was wrong, so attackers cannot use your login form to find out which emails are registered.

How does Laravel handle password hashing?

Laravel wraps the same PHP functions in its Hash facade and uses bcrypt by default:

use Illuminate\Support\Facades\Hash;

$user->password = Hash::make($request->password);
$user->save();

if (Hash::check($request->password, $user->password)) {
    // correct password
}

if (Hash::needsRehash($user->password)) {
    $user->password = Hash::make($request->password);
    $user->save();
}

If you use Laravel's built-in authentication with Auth::attempt(), it calls Hash::check() for you. Recent Laravel versions also include a 'hashed' cast on the User model, which hashes the password automatically when you set it. You can switch to Argon2 in config/hashing.php.

Common password storage mistakes

  • Using md5() or sha1(), even with a salt. They are far too fast.
  • Making the column too short. VARCHAR(60) breaks the day you move to Argon2. Use VARCHAR(255).
  • Logging passwords. Check that request logs and error reports do not record login form fields.
  • Emailing passwords. If you can email a user their password, you are storing it wrongly. Send a time-limited reset link instead.
  • No rate limiting. Limit repeated login attempts so attackers cannot guess endlessly. Laravel's throttle middleware helps here.
  • Rolling your own scheme. Use the built-in functions. They are written and reviewed by specialists.

What can users do to protect their own passwords?

Good storage on your side and good habits on the user's side work together. Share this advice with your users and follow it yourself:

  1. Use a password manager such as Bitwarden, 1Password or the one built into your browser or phone, so every account gets a long, unique password.
  2. Turn on two-factor authentication (2FA) wherever it is offered. An authenticator app is generally safer than SMS codes, which can be intercepted through SIM-swap fraud.
  3. Use passphrases made of several random words when you must remember a password.
  4. Never share OTPs or PINs. No real bank, Safaricom agent or IT support person needs them.

Protecting passwords is one part of protecting personal data, which Kenya's Data Protection Act, 2019 expects every organisation to do. If you want to build a career in this area, start with our guide to the cyber security course in Kenya.

Build secure apps from day one

Cyber Security Fundamentals is a 6-week online course (KES 15,000) that helps you understand how attackers think and how to protect the systems you build.

See the course →

Also useful: Backend Development (8 months, KES 60,000)

Frequently asked questions

Can a bcrypt hash be decrypted?

No. Hashing is one-way, so there is nothing to decrypt. An attacker can only guess passwords and hash each guess, which bcrypt makes slow on purpose.

Should I use bcrypt or Argon2id?

Either is a sound choice. Argon2id is the more modern option. bcrypt is the PHP and Laravel default and is perfectly acceptable when used with a sensible cost.

Do I need to store the salt in a separate column?

No. password_hash() stores the salt inside the hash string, and password_verify() reads it from there.

What cost should I use for bcrypt?

Start with PHP's or Laravel's default, then raise it if your server can still verify a login quickly. Test on your own hardware before changing it.

Comments (0)

Comments appear after a quick review. Your email is never shown.

You Might Also Like

SQL Injection Explained: How Attacks Work and How to Stop Them

SQL Injection Explained: How Attacks Work and How to Stop Them

Many hacked websites were not broken by clever malware. They were broken because...

Read More →
Cyber Security Course in Kenya: What It's All About, Fees and Where to Start

Cyber Security Course in Kenya: What It's All About, Fees and Where to Start

"Cyber security course in Kenya" is one of the most searched tech courses in the...

Read More →