Contextual Output Encoding
This page is outdated and no longer receives updates!
Output encoding is the process of replacing HTML control characters (e.g. <, >, ", &, etc) into their encoded representatives. This is the best mitigtion against cross-site scripting attacks.
Different contexts require different encoding types. Fortunately, there are two libraries out there to help you out. ESAPI Library from OWASP and StringEscapeUtils from Apache
Â
For data rendered in Script context:Â <script>encode for javascript here</script> ESAPI.encoder().encodeForJavaScript or StringEscapeUtils.escapeJavaScript
For data rendered in HTML context:Â <body>encode for HTML here</body> ESAPI.encoder().encodeForHtml or StringEscapeUtils.escapeHtml
For data rendered in HTML Attribute context: <div id="encode for HTML attribute here" /> ESAPI.encoder().encodeForHTMLAttributeÂ
For data rendered in URL context:Â <img src="encode for URL here" /> ESAPI.encoder().encodeForURLÂ
For data rendered in CSS context:Â <style>Encode for css here</style> ESAPI.encoder().encodeForCSS