// SECURE: Parameterized queries with validation
import java.sql.*;
import java.util.*;
import java.security.MessageDigest;
public class SecureDataService {
private Connection connection;
// Whitelisted values for security
private static final Set<String> VALID_CATEGORIES = Set.of(
"electronics", "clothing", "books", "home", "sports"
);
private static final Set<String> VALID_SORT_FIELDS = Set.of(
"name", "price", "category", "rating", "created_date"
);
private static final Set<String> VALID_SORT_DIRECTIONS = Set.of("ASC", "DESC");
public List<Product> searchProducts(String category, String minPrice, String maxPrice,
String sortField, String sortDirection) {
try {
// Validate inputs
if (!VALID_CATEGORIES.contains(category)) {
throw new IllegalArgumentException("Invalid category");
}
if (!VALID_SORT_FIELDS.contains(sortField)) {
sortField = "name"; // Default to safe value
}
if (!VALID_SORT_DIRECTIONS.contains(sortDirection.toUpperCase())) {
sortDirection = "ASC"; // Default to safe value
}
double minPriceVal = validatePrice(minPrice);
double maxPriceVal = validatePrice(maxPrice);
// Use PreparedStatement with parameters
String query = "SELECT id, name, category, price, rating, created_date " +
"FROM products WHERE category = ? AND price BETWEEN ? AND ? " +
"ORDER BY " + sortField + " " + sortDirection;
try (PreparedStatement pstmt = connection.prepareStatement(query)) {
pstmt.setString(1, category);
pstmt.setDouble(2, minPriceVal);
pstmt.setDouble(3, maxPriceVal);
ResultSet rs = pstmt.executeQuery();
return processProductResults(rs);
}
} catch (SQLException e) {
throw new RuntimeException("Database error", e);
}
}
private double validatePrice(String price) {
try {
double priceVal = Double.parseDouble(price);
if (priceVal < 0 || priceVal > 999999) {
throw new IllegalArgumentException("Price out of range");
}
return priceVal;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid price format");
}
}
}