Back to Authentication & Authorization
Q5Question 5 of 5

How do you hash and store passwords securely in Spring Boot

Answer: Password hashing converts a plain-text password into an irreversible fixed-length string using a slow, salted hash function like bcrypt or Argon2, so even if the database is compromised, the original passwords cannot be recovered.

Key Concepts
  • Never store passwords in plain text or reversible encryption; always use a one-way hash function with a unique salt.
  • bcrypt is an adaptive hash function that includes a built-in salt and a configurable cost factor to slow down brute-force attacks.
  • Argon2 is the winner of the Password Hashing Competition (2015) and resists both CPU and GPU attacks by requiring configurable memory.
  • Spring Security provides BCryptPasswordEncoder and Argon2PasswordEncoder for seamless password hashing and verification.
  • The cost factor (bcrypt strength, Argon2 memory/iterations) should be tuned so hashing takes 200-500ms on your hardware.
  • Password verification compares the hash of the input with the stored hash; the original password is never recovered.
  • Credential stuffing and rainbow table attacks are defeated by per-user salts and slow hash functions.

Definition

Password hashing converts a plain-text password into an irreversible fixed-length string using a slow, salted hash function like bcrypt or Argon2, so even if the database is compromised, the original passwords cannot be recovered.
  • Hashing is a one-way function that converts input to a fixed-length output; you cannot reverse the hash to get the original password.
  • Salt is a random value added to each password before hashing, ensuring two users with the same password get different hashes.
  • bcrypt is an adaptive password hash based on the Blowfish cipher, with a built-in salt and configurable cost factor.
  • Argon2 is a memory-hard hash function that resists GPU attacks by requiring a configurable amount of RAM during hashing.
  • Cost factor (or work factor) controls how slow the hash function is; higher values make brute-force attacks exponentially harder.

Think of the National Bank of India vault. When Rajesh creates his online banking password, the system does not write the password on a sticky note (plain text). Instead, it puts the password through a special shredder (hash function) that turns it into confetti (the hash). When Rajesh logs in later, the system shreds his input the same way and checks if the confetti matches. No one can reconstruct the password from the confetti. The salt is like adding a unique colored dye to each customer's paper before shredding: even if Rajesh and Priya use the same password, their confetti looks completely different.

Understanding the Concepts

Why should you never store passwords in plain text?

If an attacker gains access to the database (through SQL injection, a backup leak, or an insider threat), plain-text passwords give them instant access to every account. They can also try the same passwords on other systems, since most users reuse passwords.

JAVA
package com.bank.security;

public class PlainTextDangerDemo {
    public static void main(String[] args) {
        // WRONG: plain text in the database
        String storedPassword = "Rajesh@Bank2025";
        System.out.println("WRONG: Database stores: " + storedPassword);
        System.out.println("If DB is breached, attacker sees the actual password.");
        System.out.println("Attacker tries the same password on Rajesh's email.");
        System.out.println();

        // CORRECT: hash stored in the database
        String storedHash = "$2a$12$eR0dX6Y4T5FVcT8JQLA2/.b8U/8Bn.MhzZ5VBR1Nm2SqIgJcSeRbK";
        System.out.println("CORRECT: Database stores: " + storedHash);
        System.out.println("Attacker sees the hash, cannot reverse it.");
        System.out.println("Brute-force with bcrypt cost 12: ~3.5 billion years for a strong password.");
    }
}
TEXT
WRONG: Database stores: Rajesh@Bank2025
If DB is breached, attacker sees the actual password.
Attacker tries the same password on Rajesh's email.

CORRECT: Database stores: $2a$12$eR0dX6Y4T5FVcT8JQLA2/.b8U/8Bn.MhzZ5VBR1Nm2SqIgJcSeRbK
Attacker sees the hash, cannot reverse it.
Brute-force with bcrypt cost 12: ~3.5 billion years for a strong password.

How does bcrypt work?

bcrypt is based on the Blowfish cipher. It generates a random 16-byte salt, combines it with the password, and runs the Blowfish key schedule a number of times determined by the cost factor. The result is a 60-character string that contains the algorithm version, cost, salt, and hash.

JAVA
package com.bank.security;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class BcryptDemo {

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12); // cost factor 12

        String rawPassword = "Rajesh@Bank2025";
        String hash = encoder.encode(rawPassword);

        System.out.println("Password: " + rawPassword);
        System.out.println("Hash: " + hash);
        System.out.println();

        // Hash format: $2a$12$<22-char-salt><31-char-hash>
        System.out.println("Format breakdown:");
        System.out.println("  Algorithm: " + hash.substring(0, 4));
        System.out.println("  Cost: " + hash.substring(4, 6));
        System.out.println("  Salt+Hash: " + hash.substring(7));
        System.out.println();

        // Verification
        boolean matches = encoder.matches(rawPassword, hash);
        boolean wrong = encoder.matches("WrongPassword", hash);
        System.out.println("Correct password matches: " + matches);
        System.out.println("Wrong password matches: " + wrong);

        // Same password, different hash each time (different salt)
        String hash2 = encoder.encode(rawPassword);
        System.out.println();
        System.out.println("Hash 1: " + hash);
        System.out.println("Hash 2: " + hash2);
        System.out.println("Same password, different hashes: " + !hash.equals(hash2));
    }
}
TEXT
Password: Rajesh@Bank2025
Hash: $2a$12$eR0dX6Y4T5FVcT8JQLA2/.b8U/8Bn.MhzZ5VBR1Nm2SqIgJcSeRbK

Format breakdown:
  Algorithm: $2a$
  Cost: 12
  Salt+Hash: eR0dX6Y4T5FVcT8JQLA2/.b8U/8Bn.MhzZ5VBR1Nm2SqIgJcSeRbK

Correct password matches: true
Wrong password matches: false

Hash 1: $2a$12$eR0dX6Y4T5FVcT8JQLA2/.b8U/8Bn.MhzZ5VBR1Nm2SqIgJcSeRbK
Hash 2: $2a$12$Kj4x7PLm1NvR2w8TqScZX.abcdef1234567890abcdefghij1234567
Same password, different hashes: true

How is Argon2 different from bcrypt?

AspectbcryptArgon2
Year19992015 (PHC winner)
ResistanceCPU attacksCPU + GPU + ASIC attacks
MemoryFixed (~4 KB)Configurable (64 MB+)
ParametersCost factor onlyMemory, iterations, parallelism
SaltBuilt-in (16 bytes)Built-in (configurable)
Recommended forGeneral use, wide supportHigh-security: banking, government
Spring classBCryptPasswordEncoderArgon2PasswordEncoder
JAVA
package com.bank.security;

import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;

public class Argon2Demo {

    public static void main(String[] args) {
        // saltLength=16, hashLength=32, parallelism=1, memory=65536 KB (64 MB), iterations=3
        Argon2PasswordEncoder encoder = new Argon2PasswordEncoder(16, 32, 1, 65536, 3);

        String rawPassword = "Priya@Banking2025";
        long start = System.currentTimeMillis();
        String hash = encoder.encode(rawPassword);
        long elapsed = System.currentTimeMillis() - start;

        System.out.println("Password: " + rawPassword);
        System.out.println("Argon2 hash: " + hash);
        System.out.println("Time to hash: " + elapsed + " ms");
        System.out.println();

        boolean matches = encoder.matches(rawPassword, hash);
        System.out.println("Verification: " + matches);
    }
}
TEXT
Password: Priya@Banking2025
Argon2 hash: $argon2id$v=19$m=65536,t=3,p=1$<salt>$<hash>
Time to hash: 350 ms

Verification: true

How do you implement password hashing in Spring Security?

JAVA
package com.bank.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }
}
JAVA
package com.bank.service;

import org.springframework.security.crypto.password.PasswordEncoder;
import java.math.BigDecimal;

public class UserRegistrationService {

    private final PasswordEncoder passwordEncoder;

    public UserRegistrationService(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    public void register(String username, String rawPassword) {
        // Hash the password before storing
        String hashedPassword = passwordEncoder.encode(rawPassword);

        // Store username + hashedPassword in the database
        System.out.println("User: " + username);
        System.out.println("Stored hash: " + hashedPassword);
        System.out.println("Raw password is NEVER stored.");
    }

    public boolean authenticate(String rawPassword, String storedHash) {
        return passwordEncoder.matches(rawPassword, storedHash);
    }
}

What are common mistakes with password storage?

Mistake 1: Using MD5 or SHA-256 without salt

Wrong: fast hash functions like MD5 and SHA-256 can be brute-forced at billions of hashes per second.

JAVA
package com.bank.security;

import java.security.MessageDigest;
import java.util.HexFormat;

public class WeakHashDemo {
    public static void main(String[] args) throws Exception {
        // WRONG: MD5 is fast and unsalted
        String password = "Rajesh@Bank2025";
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] hash = md5.digest(password.getBytes());
        String md5Hash = HexFormat.of().formatHex(hash);

        System.out.println("WRONG: MD5 hash: " + md5Hash);
        System.out.println("Attack speed: 10 billion hashes/second on GPU");
        System.out.println("Time to crack: minutes for common passwords");
        System.out.println();
        System.out.println("CORRECT: Use bcrypt or Argon2 (200ms per hash)");
        System.out.println("Attack speed: ~5 hashes/second per GPU core");
        System.out.println("Time to crack: centuries for strong passwords");
    }
}
TEXT
WRONG: MD5 hash: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
Attack speed: 10 billion hashes/second on GPU
Time to crack: minutes for common passwords

CORRECT: Use bcrypt or Argon2 (200ms per hash)
Attack speed: ~5 hashes/second per GPU core
Time to crack: centuries for strong passwords

Mistake 2: Using the same salt for all users

Wrong: a global salt means all users with the same password get the same hash. An attacker cracks one, they crack all.

Correct: bcrypt and Argon2 generate a unique random salt per hash automatically. You do not manage salts manually.

What about password policies and brute-force protection?

Hashing protects passwords at rest. You also need runtime protections.

JAVA
package com.bank.security;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class BruteForceProtectionDemo {

    private static final int MAX_ATTEMPTS = 5;
    private static final Map<String, AtomicInteger> attempts = new ConcurrentHashMap<>();

    static boolean isBlocked(String username) {
        AtomicInteger count = attempts.get(username);
        return count != null && count.get() >= MAX_ATTEMPTS;
    }

    static void recordFailedAttempt(String username) {
        attempts.computeIfAbsent(username, k -> new AtomicInteger(0)).incrementAndGet();
    }

    static void resetAttempts(String username) {
        attempts.remove(username);
    }

    public static void main(String[] args) {
        String user = "rajesh";

        for (int i = 1; i <= 6; i++) {
            if (isBlocked(user)) {
                System.out.println("Attempt " + i + ": BLOCKED (account locked)");
            } else {
                recordFailedAttempt(user);
                System.out.println("Attempt " + i + ": Failed login");
            }
        }
    }
}
TEXT
Attempt 1: Failed login
Attempt 2: Failed login
Attempt 3: Failed login
Attempt 4: Failed login
Attempt 5: Failed login
Attempt 6: BLOCKED (account locked)

What should a senior engineer know?

- Pepper. A pepper is a secret value added to passwords before hashing, stored in application configuration (not the database). Even if the database is compromised, the attacker cannot crack hashes without the pepper. Spring Security does not provide built-in pepper support, so you prepend it manually before encoding.

- Adaptive cost factor. Increase the bcrypt cost factor as hardware improves. When your server can hash in under 100ms at cost 12, bump to cost 13. Re-hash existing passwords during the next login by detecting the old cost in the stored hash.

- Credential stuffing defense. Attackers use leaked password databases from other breaches. Defend with rate limiting, CAPTCHA after failed attempts, and checking passwords against the Have I Been Pwned API.

- Hardware security modules (HSM). For banking compliance, store the pepper and encryption keys in an HSM (AWS CloudHSM, Azure Dedicated HSM). The HSM performs cryptographic operations without exposing the key material.

- Password migration. When migrating from MD5 to bcrypt, wrap the old hash: bcrypt(md5(password)). On the next login, re-hash with bcrypt directly and update the stored hash.

What are common interview follow-up questions?

  • What is the difference between hashing and encryption?
  • Why is bcrypt better than SHA-256 for password storage?
  • What is a rainbow table and how does salting prevent it?
  • How do you migrate password hashes from an old algorithm to a new one?
  • What is the OWASP recommendation for password storage?

Visual Overview

DIAGRAM
  Password Hashing Flow
  ======================

  Registration:
  Password: "Rajesh@Bank2025"
       │
       ▼
  Generate random salt (16 bytes)
       │
       ▼
  bcrypt(password + salt, cost=12)
       │
       ▼
  Store: $2a$12$<salt><hash>    (in database)
  Password is NEVER stored.


  Login Verification:
  Input: "Rajesh@Bank2025"
       │
       ▼
  Extract salt from stored hash
       │
       ▼
  bcrypt(input + extracted salt, cost=12)
       │
       ▼
  Compare computed hash with stored hash
       │
       ├── Match    -> Login successful
       └── No match -> Login failed


  Attack Resistance
  ==================
  Algorithm    Speed (GPU)          Time to crack
  ─────────    ─────────────────    ─────────────
  MD5          10 billion/sec       minutes
  SHA-256      5 billion/sec        minutes
  bcrypt-12    5/sec per core       centuries
  Argon2       2/sec per core       centuries+

Key Takeaway

Password hashing is the last line of defense for customer credentials. At the National Bank of India, if an attacker breaches the database through SQL injection, the only thing standing between them and every customer's account is the strength of the password hash. Plain text or fast hashes like MD5 offer no protection. bcrypt and Argon2 are slow by design, turning a brute-force attack from minutes into centuries.

bcrypt has been the industry standard since 1999. It generates a unique random salt for each password, includes the salt in the hash output, and uses a configurable cost factor. Spring Security's BCryptPasswordEncoder handles everything: hashing, salt generation, and verification. You never store or manage salts separately.

Argon2 is the newer, stronger choice. It requires configurable memory (64 MB or more) during hashing, which makes GPU-based attacks impractical because GPUs have limited memory per core. For new banking applications, Argon2 is the recommended choice. For existing applications already using bcrypt, there is no urgent need to migrate, but new services should default to Argon2.

The cost factor should be tuned so that hashing takes 200-500ms on your production hardware. Too fast means easier brute-force. Too slow means slow logins and denial-of-service risk. Test and adjust annually as hardware improves.

One sentence to remember: hash passwords with bcrypt or Argon2, never store them in plain text, and tune the cost factor so each hash takes at least 200 milliseconds.

---

Share
Use ← → arrow keys to navigate