Gokul
1 min readDec 24, 2016

--

ESAPI’s encodeForHTML vs encodeForHTMLAttribute

What is the difference between, ESAPI’s encodeForHTML vs encodeForHTMLAttribute?

One of frequent FAQ from my teammates.

Here is an example outputs.

$ESAPI.encoder().encodeForHTML(“<h1> Header</h1>”);

“&lt;h1&gt; Header&lt;&#x2f;h1&gt;”

$ESAPI.encoder().encodeForHTMLAttribute(“<h1> Header</h1>”);

“&lt;h1&gt;&#x20;Header&lt;&#x2f;h1&gt;”

Got it?

Okay, the encodeForHTMLAttribute will encode “THE EMPTY SPACE”(“&#x20;”).

Where to Use ?

encodeForHTML()

When we want put user inputs or untrusted data into HTML tags like body, div, span, li, p, b, td, header tags.

Usage
<div>encodeForHTML(UserInputs/untrusted data)</div>

encodeForHTMLAttribute()

When we want put user inputs or un-trusted data into HTML attributes like value, name, id, width.

Usage
<input type=”button” value=”encodeForHTMLAttribute(UserInputs/untrusted data)” />

Why should encode an empty space, what will achieve with this encode ?

<%
String aValueName = request.getParameter(“aValueNameFromUser”);

// aValueNameFromUser : “a\” onmouseover=\”alert(1)\””
%>

<input type=”button” value=”<%=aValueName%>” name=”<%=aValueName%>” />

In above source, button value and name will set from user input(“”a\” onmouseover=\”alert(1)\”) and that user input will add “onmouseover” attribute to input tag and it will execute if user input has any XSS or script. We must encode the "The Empty Space" to avoid such XSS attacks. So encodeForHTMLAttribute() is best choice for that.

--

--

Gokul

Lying in Clouds, Trying to be secure, coding like a poet, fool like a philosopher