1. import java.util.regex.Pattern;
  2. public class InputSanitizer {
  3. // Method to sanitize a string input
  4. public static String sanitizeInput(String input) {
  5. if (input == null || input.isEmpty()) {
  6. return ""; // Return empty string for null or empty input
  7. }
  8. // Remove HTML tags
  9. input = stripHtmlTags(input);
  10. // Remove special characters (keep alphanumeric and spaces)
  11. input = allowAlphanumericAndSpaces(input);
  12. // Optional: Limit length
  13. // input = limitLength(input, 255); // Example: Limit to 255 characters
  14. return input;
  15. }
  16. // Removes HTML tags
  17. private static String stripHtmlTags(String input) {
  18. Pattern pattern = Pattern.compile("<[^>]*>");
  19. return pattern.matcher(input).replaceAll("");
  20. }
  21. // Allows only alphanumeric characters and spaces
  22. private static String allowAlphanumericAndSpaces(String input) {
  23. return input.replaceAll("[^a-zA-Z0-9\\s]", "");
  24. }
  25. // Optional: Limits the length of the string. Can be computationally expensive for large strings.
  26. private static String limitLength(String input, int maxLength) {
  27. if (input.length() > maxLength) {
  28. return input.substring(0, maxLength);
  29. }
  30. return input;
  31. }
  32. public static void main(String[] args) {
  33. String testInput = "<script>alert('XSS')</script> Hello, World! & Special chars: !@#$%^&*()_+=-`~[]\{}|;':\",./<>?";
  34. String sanitizedInput = sanitizeInput(testInput);
  35. System.out.println("Original Input: " + testInput);
  36. System.out.println("Sanitized Input: " + sanitizedInput);
  37. }
  38. }

Add your comment