Saturday, June 16, 2012

Escaping HTML in JAVA using Apache Commons Lang

Anytime you display data that a user entered on a public site you should escape the data to prevent Javascript injection attacks. Here is a cool site with a multitude of possible injections: ha.ckers.org

To escape text you display you can use the Apache Commons Lang library for Java. You can head over to the official site to download the binary and add the JAR files to your project. Once done escaping data is super easy:
<%@page import="org.apache.commons.lang3.StringEscapeUtils"%>

 <%
        String attackScript = "<IMG SRC=javascript:alert('XSS')>";
        String results = StringEscapeUtils.escapeHtml4(attackScript);
        out.print(results);
%>

That is all there is too it. Works just like html_entities() in PHP.  Finally, the documentation for the package is here.

No comments:

Post a Comment