PasswordEncoder – Secure Password Handling - VittorioDeMarzi/hero-beans GitHub Wiki

🔐 PasswordEncoder – Secure Password Handling

1. What it does

This class wraps the BCrypt hashing algorithm to:

  • Encode plain text passwords before storing them in the database.
  • Verify raw passwords against their hashed (encoded) versions during authentication.

It ensures that no plain-text passwords are ever stored or compared directly.


2. Why we use it

  • Security:
    • BCrypt is a well-established, secure hashing algorithm for passwords.
    • It’s salted automatically — every hash includes a unique random salt, making rainbow table attacks ineffective.
    • It’s computationally expensive, which slows down brute-force attacks.
  • Best practice: Storing raw passwords is never safe; hashing them is a security standard.
  • Compatibility: BCrypt hashes are widely supported across languages and frameworks.

3. How this configuration works

  • encode(rawPassword: String)

    • Uses BCrypt.hashpw() with a newly generated salt (BCrypt.gensalt()).

    • Produces a string like:

      $2a$10$N9qo8uLOickgx2ZMRZoMyeIjZxXh0lO4fQUMMR5lH3tFIUmyiD7KC
      

      which contains:

      • Algorithm version ($2a$)
      • Work factor (e.g., 10 rounds)
      • Salt and hash
  • matches(rawPassword, encodedPassword)

    • Uses BCrypt.checkpw() to hash the raw input and compare it to the stored hash.
    • Wrapped in a try/catch to safely return false if the stored hash is malformed or corrupted.

4. How to use in your project

Example: Encoding on registration

val encoded = passwordEncoder.encode("myPassword123")
// Save `encoded` to the database

Example: Verifying on login

val isValid = passwordEncoder.matches("myPassword123", storedHash)
if (isValid) {
    // proceed with authentication
} else {
    // reject login
}

5. Why configured like this

  • Encapsulation:

    • Provides a simple, reusable interface for password handling.
    • Keeps BCrypt-specific code in one place — easier to change algorithm later if needed.
  • Safety checks:

    • Catches exceptions during verification to avoid breaking login flow due to corrupted data.
  • Salt handling:

    • No need to manually store salts — BCrypt embeds them in the hash.