Is this Java method good for protecting against cross-site scripting? It is a Servlet running in Jetty. The input comes from the user's HTTP request (we need to do stuff with the URI, parameter values, header values, and body), we clean it, and the output is a reflection of the cleaned input as HTTP response for the user's browser.
String clean(String tainted) {
String cleaned = "";
for (int i = 0; i < tainted.length(); i++) {
char c = tainted.charAt(i);
switch (c) {
case '&': cleaned += "&"; break;
case '<': cleaned += "<"; break;
case '>': cleaned += ">"; break;
default:
if (Character.isISOControl(c) && !Character.isWhitespace(c)) {
cleaned += '?';
} else {
cleaned += c;
}
}
}
return cleaned;
}
String doStuff(String clean) {...}
return "<!DOCTYPE html><html><body>" + doStuff(clean(userInput)) + "</body></html>";