Why encoding matters to a hacker
Data on the web never travels as "just text". It is wrapped, escaped, packed and unpacked several times between your keyboard and a database: your browser percent-encodes it into a URL, a proxy decodes part of it, a framework parses it into a structure, a template escapes it for HTML, a database driver quotes it for SQL. Each of these steps has its own encoding and its own decoder.
Many vulnerabilities are really decoding mistakes:
- A filter checks the data before a decode step; the application uses it after. The payload slips through (
%3Cscript%3Epasses a filter that looks for<script>). - Data is decoded twice (double decoding), so a once-encoded payload becomes dangerous at the second stage.
- Data is escaped for the wrong context (HTML-escaped but then placed inside a JavaScript string or a URL).
- Two components disagree about how to decode the same bytes (UTF-8 vs Latin-1,
+vs%20).
If you understand encodings you can read payloads, build bypasses and, most importantly, understand why a defense that looked solid fails. This lesson covers the formats you will meet every day.
Encoding is not encryption and not hashing. Encoding is a reversible, keyless representation change. It provides no secrecy. A value that is "just Base64" is plain text to an attacker.
Characters, bytes and Unicode
A computer stores bytes. Text is bytes interpreted through a character encoding.
- ASCII maps 128 characters to the values 0 to 127.
- Unicode assigns a number (a code point) to every character in every language, written
U+0041forA,U+00E9foré,U+1F600for an emoji. - UTF-8 is the dominant way to store Unicode as bytes: variable length, 1 to 4 bytes per code point, and the first 128 code points are identical to ASCII.
| Character | Code point | UTF-8 bytes (hex) |
|---|---|---|
A |
U+0041 | 41 |
é |
U+00E9 | C3 A9 |
€ |
U+20AC | E2 82 AC |
😀 |
U+1F600 | F0 9F 98 80 |
Security consequences of Unicode:
- Normalization. The same visible character can have several representations (
éas one code point, oreplus a combining accent). Some systems normalize (NFC, NFKC, NFKD) after validating, soSCRIPT(full-width letters) can turn into ASCII equivalents after a filter ran. - Case mapping surprises. Uppercasing or lowercasing certain characters changes their length or produces ASCII (
ı,ſ, the Kelvin signK). This has broken blocklists and account-uniqueness checks. - Homograph attacks. Cyrillic
аlooks like Latina. Browsers show suspicious internationalized domains in punycode (xn--...) to counter this. - Overlong UTF-8. Historically,
%C0%AFwas an invalid longer encoding of/accepted by some decoders, enabling path traversal bypasses. Modern decoders reject it, but parsers still disagree. - Charset mismatch. If the server says
Content-Type: text/htmlwithout a charset and the page uses a different one (for example UTF-7 in old attacks), the browser may interpret bytes differently from what the filter assumed. Always declarecharset=utf-8.
URL encoding (percent-encoding)
URLs may contain only a limited set of characters. Anything else is written as % followed by the two hex digits of the byte value. Reserved characters (/ ? # & = + : and others) have special meaning, so when used as data they must be encoded.
| Character | Encoded | Notes |
|---|---|---|
| space | %20 or + |
+ means space only in query strings and form bodies |
< |
%3C |
|
> |
%3E |
|
" |
%22 |
|
' |
%27 |
|
/ |
%2F |
|
\ |
%5C |
|
& |
%26 |
|
= |
%3D |
|
# |
%23 |
|
% |
%25 |
The escape character itself |
é |
%C3%A9 |
UTF-8 bytes, each percent-encoded |
| null byte | %00 |
Historically truncated strings in C-based code |
Example: a search for a&b=c d placed in a query string must be sent as:
GET /search?q=a%26b%3Dc%20d HTTP/1.1
If you sent q=a&b=c d raw, the server would see two parameters, q and b. That is the basis of HTTP parameter pollution and injection of extra parameters.
Practical notes:
- Browsers encode some characters automatically but not all. For instance the address bar leaves
'and<less consistently encoded thanfetch()orURLSearchParamsdo. Your proxy shows the raw bytes sent. - When testing, you often must encode characters yourself in a proxy so they are not interpreted by the transport. Typing
&inside a value in Burp's query view will split the parameter, so use%26. - Encode only the characters that need it, or all characters (
%61forais legal), depending on what the filter looks for.
Double encoding
If one layer decodes once and another decodes again, you can encode the encoding:
| Stage | Value |
|---|---|
| Attacker sends | %253Cscript%253E |
| After first decode (proxy/WAF) | %3Cscript%3E (harmless-looking, passes the check) |
| After second decode (application) | <script> |
%25 is the encoding of %, so %253C decodes to %3C, and then to <. The same trick turns ..%252f into ../ for path traversal. A real example of the pattern: a front-end enforces /admin restrictions on the decoded-once path, while the backend decodes again and serves the admin resource.
You can test for double decoding by sending a harmless marker: request /x%252Fy versus /x%2Fy versus /x/y and compare responses.
HTML entities (HTML encoding)
In HTML, certain characters are special: < starts a tag, & starts an entity, " and ' end attribute values. To display them literally, HTML uses entities:
| Character | Named | Decimal | Hex |
|---|---|---|---|
< |
< |
< |
< |
> |
> |
> |
> |
& |
& |
& |
& |
" |
" |
" |
" |
' |
' (or ') |
' |
' |
Output encoding for HTML is the primary defense against XSS: if the server turns <script> into <script>, the browser shows the text instead of running it. But:
- Encoding must match the context. HTML-encoding is correct between tags and in quoted attributes, but it is not sufficient inside a
<script>block, in anhref/srcattribute (ajavascript:URL needs no special characters), or inside CSS. Each context needs its own escaping. - Browsers decode entities inside attribute values before using them.
<a href="javascript:alert(1)">is ajavascript:link, a classic way to bypass filters that look for the literal string. - Entities without semicolons and with leading zeros (
j) are accepted by some parsers. - Encoding twice (
&lt;) displays literally<, which is a classic sign of double-encoding bugs in the display layer.
Base64
Base64 turns arbitrary bytes into 64 safe ASCII characters (A-Z a-z 0-9 + /, with = padding) so binary can travel through text-only channels. Every 3 bytes become 4 characters, so output is about 33 percent larger.
echo -n 'admin:secret' | base64
# YWRtaW46c2VjcmV0
echo 'YWRtaW46c2VjcmV0' | base64 -d
In a browser console: btoa('admin:secret') and atob('YWRtaW46c2VjcmV0').
You will see Base64 in:
Authorization: Basic YWRtaW46c2VjcmV0(the credentials, trivially reversible).- JWTs, which use Base64URL, a variant replacing
+and/with-and_and dropping padding. - Cookies that store serialized data (often a deserialization target) or user state.
- Data URLs, emails, certificates (PEM), API keys.
Spotting Base64: a string of letters and digits that is a multiple of 4 long (before padding removal), ending with = or ==, and often starting with recognizable prefixes: eyJ is Base64 of {" (JSON), rO0 is the start of a Java serialized object, Tzo is PHP O: serialized object.
Base64 is encoding, not security. "Hiding" a role, price or id inside Base64 in a cookie or parameter protects nothing; decode it, change it, re-encode it.
Hexadecimal
Hex writes each byte as two characters 00 to ff. It appears in hashes (5f4dcc3b5aa765d61d8327deb882cf99 is MD5 of "password"), memory dumps, color codes, \x41 escapes in strings, 0x41 in code, and SQL (0x61646d696e is admin, useful to bypass quote filters in MySQL). The notation varies: %41 (URL), \x41 (JavaScript, C), A (JavaScript Unicode), A (HTML), 0x41 (programming). Same value, different decoder.
echo -n 'admin' | xxd -p # 61646d696e
echo '61646d696e' | xxd -r -p # admin
JSON
JSON (JavaScript Object Notation) is the dominant API format:
{"id": 42, "name": "Alice", "roles": ["user"], "profile": {"newsletter": true}}
Types: object, array, string, number, true/false, null. Strings use double quotes and support escapes: \", \\, \n, < (which is <).
Security angles:
- Escapes bypass naive filters.
"<script>"is<script>after the JSON parser runs, but not before. - Type confusion. Sending
{"user": {"$ne": null}}to a MongoDB-backed login (NoSQL injection), or{"id": [1,2]}where a number was expected. - Mass assignment. Adding fields the form never sends, such as
"role": "admin"or"isVerified": true. - Duplicate keys.
{"role":"user","role":"admin"}parsers disagree on which wins. - JSON hijacking and content-type sniffing when JSON is served with the wrong
Content-Type. - Sending JSON where a form was expected (or vice versa) may skip validation and CSRF defenses.
XML
XML is verbose and structured with tags and attributes; it powers SOAP, SAML, RSS, SVG, Office documents and many legacy APIs.
<?xml version="1.0"?>
<user><name>Alice</name><email>[email protected]</email></user>
Special characters use entities: <, >, &. XML also supports a DTD with custom entities, including external entities that can read local files or make server-side requests when parsers are not hardened: XXE (XML External Entity injection). Other risks: XML bombs (entity expansion), XPath injection, signature wrapping in SAML, and SVG files containing scripts. Many servers that normally accept JSON will also accept XML if you change the Content-Type.
Multipart form data
When a form uploads files or mixes fields and files, the browser uses multipart/form-data. The body is split into parts separated by a boundary declared in the header:
POST /profile HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4
------WebKitFormBoundary7MA4
Content-Disposition: form-data; name="displayName"
Alice
------WebKitFormBoundary7MA4
Content-Disposition: form-data; name="avatar"; filename="me.png"
Content-Type: image/png
<bytes of the file>
------WebKitFormBoundary7MA4--
Each part has its own headers, all attacker-controlled: name, filename (path traversal such as ../../x.php, double extensions a.php.jpg, null bytes), and Content-Type (spoofable). WAFs and servers that parse multipart differently can be bypassed, for example with duplicate parameters, odd whitespace or line endings, or unusual boundaries.
Encoding and the order of operations
The key skill is thinking in a pipeline of transformations. For any input, trace:
- What encoding does it arrive in (URL, JSON, multipart, Base64 inside JSON)?
- Who decodes it, in what order?
- At which point does a security check run (before or after decoding, normalization, case folding)?
- What context does the final value land in (HTML body, attribute, JS string, SQL, shell, file path, URL)?
If a check runs earlier than a decode, encode the payload so the check cannot recognize it. If the final context needs a particular encoding, find characters that survive and still break out of it. Common transformations to try when a payload is blocked:
| Try | Example |
|---|---|
| URL-encode once or twice | %3C, %253C |
| Mixed case | ScRiPt |
| HTML entities in attributes | javascript: |
| Unicode escapes | <, \x3c |
| Alternative whitespace | %09, %0a, %0c, /**/ in SQL |
| Different charsets/normalization | full-width or compatibility characters |
| Content-Type switch | form to JSON or XML |
Bypassing encoding-based filters is an engineering skill, not a magic list. Always identify the actual decoder and context first; blind payload spraying wastes time and creates noise.
Hands-on exercises
- Hand-encode a URL. Take
https://example.com/search?q=cats & dogs=1. Encode it correctly and test it in DevTools Console withencodeURIComponent('cats & dogs=1'), then compare withencodeURI(...). What is the difference? - Base64 round trip. In the Console:
btoa('role=user'), change the text torole=admin, re-encode, and decode withatob. Then decode the middle part of any JWT (atob(token.split('.')[1].replace(/-/g,'+').replace(/_/g,'/'))) from a test site. - See entities do their job. Create a local HTML file with
<p><b>bold</b> and <b>bold</b></p>and<a href="javascript:alert(1)">test</a>(opened locally). Inspect the DOM in the Elements tab and see how the entities were decoded before the browser used them. - Spot double encoding. Type
%2541in the address bar of a page that echoes the path or query on a practice app, and see whether it displays%41orA. Which layer decoded how many times? - Inspect multipart. In the Network tab, upload a file to a practice form, open the request and view the raw payload. Identify boundary, field names, filename and part content type.
- Compare Unicode. In the Console, run
'é'.length,'é'.length,'é' === 'é', and'é'.normalize() === 'é'.normalize(). Explain why validation after normalization is safer. - Use a decoder. When you finish the proxy lesson, repeat these conversions with Burp's Decoder or CyberChef (a free web tool) and chain them (URL then Base64).
Checklist
- I can URL-encode and decode by hand for the common special characters.
- I can recognize Base64, hex, percent-encoding and entities at a glance.
- I can explain double encoding with a worked example.
- I know why context decides which escaping is correct.
- I can explain why checks must run after decoding and normalization.
- I know the main security risks of JSON, XML and multipart.
- I never confuse encoding with encryption.
Key takeaways
- Every layer has its own decoder; vulnerabilities live in the gaps between them.
- Validate after decoding and normalization, and escape for the output context.
- Double encoding, Unicode tricks and format switching are standard bypass families.
- Encodings such as Base64 hide nothing; treat encoded client data as plain, editable input.
- Think in pipelines: what arrives, who decodes it, where it lands.
Further reading
- RFC 3986 (URI), RFC 4648 (Base64), RFC 8259 (JSON), RFC 3629 (UTF-8)
- MDN: Percent-encoding,
encodeURIComponent, character references (HTML entities) - WHATWG URL Standard and Unicode Technical Report 15 (normalization)
- OWASP: Cross Site Scripting Prevention Cheat Sheet (output encoding by context), XXE Prevention Cheat Sheet
- PortSwigger Web Security Academy: XSS contexts, path traversal, XXE, and the "Obfuscating attacks using encodings" topic