Class PasswordUtil

java.lang.Object
com.ntu.fdae.group1.bto.utils.PasswordUtil

public final class PasswordUtil extends Object
Utility class for handling password hashing and verification using PBKDF2WithHmacSHA256. This class implements secure password handling following industry best practices:
  • Uses PBKDF2 (Password-Based Key Derivation Function 2) with HMAC-SHA256
  • Employs random salting to prevent rainbow table attacks
  • Applies multiple iterations to increase computational cost for attackers
  • Implements timing-attack resistant comparison for verification
  • Stores password data in a standardized format for persistence

The password storage format is: base64(salt)$iterations$base64(hash)

This implementation follows OWASP security recommendations for password storage and is intended to be used for all password handling in the BTO Management System.

  • Method Details

    • hashPassword

      public static String hashPassword(String plainPassword)
      Hashes the given plain-text password using PBKDF2WithHmacSHA256 with a newly generated salt and configured iteration count. This method:
      1. Generates a cryptographically secure random salt
      2. Applies the PBKDF2 algorithm to derive a hash
      3. Encodes both salt and hash using Base64
      4. Combines them with the iteration count into a single storage-ready string
      Parameters:
      plainPassword - The password to hash. Must not be null.
      Returns:
      A string containing the Base64 encoded salt, iteration count, and Base64 encoded hash, separated by delimiters (e.g., "base64(salt)$iterations$base64(hash)").
      Throws:
      NullPointerException - if plainPassword is null
      RuntimeException - if the PBKDF2 algorithm is not available or if the key specification is invalid.
    • verifyPassword

      public static boolean verifyPassword(String plainPassword, String hashedPassword)
      Verifies a plain-text password against a stored combined salt, iterations, and hash string. This method:
      1. Parses the stored password string to extract salt, iterations, and hash
      2. Re-computes the hash using the provided plain-text password, extracted salt, and iterations
      3. Compares the computed hash with the stored hash using a constant-time comparison to prevent timing attacks
      Parameters:
      plainPassword - The plain-text password entered by the user. Must not be null.
      hashedPassword - The combined string retrieved from storage (format: "base64(salt)$iterations$base64(hash)"). Must not be null.
      Returns:
      true if the password matches the stored hash, false otherwise.
      Throws:
      NullPointerException - if either parameter is null
      IllegalArgumentException - if the storedCombinedPassword format is invalid.
      RuntimeException - if the PBKDF2 algorithm is not available or if the key specification is invalid during verification.