0

In my java app I'm preventing XSS attacks. I want to encode URL and hidden field paramaters in the HttpServletRequest objects I have a handle on.

How would I go about doing this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
AJM
  • 32,054
  • 48
  • 155
  • 243

3 Answers3

2

Don't do that. You're making it unnecessarily more complicated. Just escape it during display only. See my answer in your other topic: Java 5 HTML escaping To Prevent XSS

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

To properly display user-entered data on an HTML page, you simply need to ensure that any special HTML characters are properly encoded as entities, via String#replace or similar. The good news is that there is very little you need to encode (for this purpose):

str = str.replace("&", "&amp;").replace("<", "&lt;");

You can also replace > if you like, but there's no need to.

This isn't only because of XSS, but also just so that characters show up properly. You may also want to handle ensuring that characters outside the common latin set are turned into appropriate entities, to protect against charset issues (UTF-8 vs. Windows-1252, etc.).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • You need `"` as well, otherwise content in attributes won't be safe. – Kornel Dec 11 '10 at 23:40
  • @porneL: Only if the output in question is being output as an attribute value, and only if you've used double quotes to quote the attribute (HTML allows either single or double quotes for quoting attributes). – T.J. Crowder Dec 11 '10 at 23:46
0

You can use StringEscapeUtils from the library Apache Jakarta Commons Lang

http://www.jdocs.com/lang/2.1/org/apache/commons/lang/StringEscapeUtils.html

Mike
  • 2,354
  • 3
  • 23
  • 37