How can dynamic salts be implemented in PHP for password hashing to enhance security?
Dynamic salts can be implemented in PHP for password hashing by generating a random salt for each user during the registration process. This adds an extra layer of security by ensuring that even if two users have the same password, their hashed passwords will be different due to the unique salt used. This prevents attackers from using precomputed rainbow tables to crack passwords.
// Generate a random salt for each user during registration
$salt = bin2hex(random_bytes(16));
// Hash the password using the generated salt
$hashedPassword = password_hash($password . $salt, PASSWORD_DEFAULT);
// Store the hashed password and salt in the database
$stmt = $pdo->prepare("INSERT INTO users (username, password, salt) VALUES (:username, :password, :salt)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $hashedPassword);
$stmt->bindParam(':salt', $salt);
$stmt->execute();