ShiftTools ShiftTools
Web Security & Utilities

How to Encode and Decode Base64, URL, and HTML Entities

Published: Sep 2026 • 6 min read • By ShiftTools Engineering Team

How to Encode and Decode Base64, URL, and HTML Entities

Data Representation & Web Security Sep 2026 17 min read 100% In-Browser

In modern distributed systems, web development, network engineering, and cybersecurity, data rarely travels in its raw native format. High-throughput communication protocols, database query parameters, RESTful APIs, and web browsers constantly translate information across multiple encoding abstractions to guarantee safe transit through heterogeneous network hardware.

Binary images, cryptographic keys, authentication signatures, and serialized payloads are transformed into Base64 ASCII strings. Complex query parameters containing spaces, slashes, and unicode emojis are transformed into RFC 3986 percent-encoded URL strings. User inputs rendered within web pages are transformed into HTML entities to neutralize Cross-Site Scripting (XSS) attack vectors.

However, engineers and security analysts attempting to inspect or decode authorization headers, JWT payloads, or webhook signatures frequently rely on dubious online utility websites. Pasting sensitive authentication tokens or proprietary API secrets into third-party cloud tools exposes corporate credentials to immediate risk. The ShiftTools Encoder & Decoder executes all Radix-64, percent-encoding, and entity parsing routines 100% locally in your browser memory, ensuring complete privacy, zero latency, and universal multi-byte UTF-8 compliance.

Looking for an instant, private Multi-Format Encoder & Decoder?

Encode and decode Base64, URL percent-encoding, and HTML entities securely in your browser with full UTF-8 support.

Launch Encoder & Decoder

1. The Mathematics of Base64 Binary-to-Text Encoding

Formalized in IETF **RFC 4648**, Base64 is a Radix-64 encoding scheme designed to represent arbitrary binary byte streams using an alphabet of 64 printable US-ASCII characters. This ensures binary data can travel through legacy 7-bit email protocols (MIME), HTTP headers, and JSON payloads without risk of character corruption or control code truncation.

1.1 The 3-Byte to 4-Character Mapping Mechanics

The mathematical core of Base64 relies on the lowest common multiple between 8-bit bytes and 6-bit indices (LCM(8, 6) = 24 bits):

  1. The encoder reads binary data in sequential chunks of **3 bytes** (3 × 8 = 24 bits).
  2. These 24 contiguous bits are partitioned into **4 groups of 6 bits** each (4 × 6 = 24 bits).
  3. Each 6-bit integer (ranging from 0 to 63) serves as an index into the standardized 64-character alphabet table:
    • Indices 0 - 25 map to uppercase ASCII A - Z
    • Indices 26 - 51 map to lowercase ASCII a - z
    • Indices 52 - 61 map to numeric digits 0 - 9
    • Index 62 maps to + (plus)
    • Index 63 maps to / (slash)

Because 3 input bytes become 4 output ASCII characters, Base64 encoding introduces a deterministic **33.3% data size overhead**:

Output_Length = \lceil N / 3 \rceil \times 4

1.2 Padding Rules with '=' Characters

When the input byte length \( N \) is not an exact multiple of 3, padding is required:

  • If **1 byte** remains at the end (8 bits), 4 zero bits are appended to complete two 6-bit blocks. The remaining two character positions are filled with two = padding characters (e.g., QQ==).
  • If **2 bytes** remain at the end (16 bits), 2 zero bits are appended to complete three 6-bit blocks. The final character position is filled with one = padding character (e.g., QUI=).

1.3 Base64 vs. Base64URL

In web architectures, standard Base64 characters + and / introduce severe URL routing errors. Web servers interpret + as an encoded space and / as a directory path separator.

To solve this, **RFC 4648 §5** defined the **Base64URL** standard:

Standard Base64:  +  and  /  with  =  padding
Base64URL:        -  and  _  without padding

Base64URL is the universal foundation of JSON Web Signatures (JWS), JSON Web Tokens (JWT), and OAuth2 state tokens. ShiftTools supports one-click toggling between Standard Base64 and Base64URL.

2. The UTF-8 Multi-Byte Dilemma in JavaScript

A notorious bug in web applications is the failure of JavaScript's built-in window.btoa() and window.atob() functions when handling unicode text:

// Legacy JavaScript Error:
btoa("Hello, World - Unicode éèà");
// Uncaught DOMException: The string to be encoded contains characters
// outside of the Latin1 range.

Because btoa was designed in the early 1990s, it expects each JavaScript string character to correspond to a single 8-bit Latin-1 code unit. Modern unicode characters—such as Chinese, Japanese, Arabic, Cyrillic, and emojis—occupy between 2 and 4 bytes per character in UTF-8.

ShiftTools bypasses legacy APIs entirely by using the modern W3C **Encoding API** (`TextEncoder` and `TextDecoder`):

// ShiftTools Universal UTF-8 Base64 Pipeline
function utf8ToBase64(str) {
  const encoder = new TextEncoder();
  const bytes = encoder.encode(str); // Produces Uint8Array of UTF-8 bytes
  let binary = '';
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}

function base64ToUtf8(b64) {
  const binary = window.atob(b64);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }
  const decoder = new TextDecoder();
  return decoder.decode(bytes); // Pristine UTF-8 reconstruction
}

This modern typed-array pipeline guarantees zero data corruption across any language, script, or emoji sequence.

3. RFC 3986 URL Percent-Encoding Mechanics

Uniform Resource Identifiers (URIs) are constrained by the **RFC 3986** specification to a small subset of the ASCII character set. Any character outside the unreserved character set must be represented using percent-encoding (a percent sign % followed by two hexadecimal digits representing the character's byte value).

3.1 Reserved vs. Unreserved Characters

Character Class Characters Handling Rules
Unreserved A-Z, a-z, 0-9, -, _, ., ~ Never encoded; transmitted as literal ASCII.
Reserved (Sub-delims) !, $, &, ', (, ), *, +, ,, ;, = Encoded when used as literal parameter data; unencoded when used as structural URI separators.
Reserved (Gen-delims) :, /, ?, #, [, ], @ Must be encoded inside query parameter values to prevent breaking URI scheme, host, and path hierarchies.
Non-ASCII / Space Space (%20 or +), UTF-8 bytes (e.g., %C3%A9) Always percent-encoded as individual UTF-8 octets.

3.2 Architectural Distinction: encodeURI vs. encodeURIComponent

In frontend engineering, misusing URI encoding functions causes breaking production bugs:

  • encodeURI(completeURL): Preserves protocol separators (https://), query boundaries (?), and parameter separators (&). Use this when encoding an entire, assembled URL.
  • encodeURIComponent(paramValue): Ruthlessly encodes all reserved characters including :, /, ?, and &. Use this whenever injecting user input or dynamic values into a specific query parameter:
    // Correct Query String Assembly:
    const search = "C++ / C# & Python";
    const url = "https://api.example.com/search?q=" + encodeURIComponent(search);
    // Result: https://api.example.com/search?q=C%2B%2B%20%2F%20C%23%20%26%20Python

4. HTML Entity Encoding and XSS Sanitization

When web applications display user-supplied text inside an HTML document without sanitization, an attacker can inject malicious markup that executes arbitrary JavaScript—the classic **Reflected or Stored Cross-Site Scripting (XSS)** vulnerability.

HTML entity encoding replaces sensitive markup delimiters with their corresponding entity representations:

&  -->  &amp;   (Ampersand)
<  -->  &lt;    (Less than - open tag)
>  -->  &gt;    (Greater than - close tag)
"  -->  &quot;  (Double quotation mark)
'  -->  &#39;   (Single quotation mark / apostrophe)

ShiftTools provides bidirectional encoding: convert raw text into named, decimal, or hexadecimal HTML entities, and decode legacy HTML entities back into clean, readable plaintext.

Security Engineering Tip: Context-Aware Sanitization

HTML entity encoding protects text rendered inside normal HTML elements (such as <p> or <span>). However, entity encoding does NOT protect against injection inside <script> tags, HTML event handlers (e.g., onclick="..."), or CSS contexts. Always combine HTML entity encoding with robust Content Security Policy (CSP) headers.

5. Step-by-Step Guide with ShiftTools

Encoding or decoding data payloads with ShiftTools takes only three steps:

Select Transformation Mode

Choose between Base64 (Standard or Base64URL), URL Percent-Encoding (Full URL or Component), or HTML Entities (Named, Decimal, Hexadecimal).

Input Text or Drag Binary File

Type or paste your raw strings, tokens, or code snippets directly into the input area. Alternatively, drop a local binary file (image, PDF, audio) to instantaneously generate its Data URI Base64 representation.

Copy Output or Download Binary Asset

Click copy to grab the transformed payload. When decoding Base64 binary strings, click 'Download File' to reconstruct the original binary asset directly to disk.

6. Absolute Client-Side Security Guarantees

Engineers routinely inspect sensitive cryptographic material: AWS secret access keys, JWT authorization bearer tokens, hashed database passwords, and OAuth refresh credentials. Pasting these strings into public online decoders is a catastrophic security vulnerability that has repeatedly led to corporate breaches.

ShiftTools guarantees absolute client-side execution. The application contains zero tracking beacons, makes zero remote API requests, and executes all string manipulations exclusively in the browser's local sandbox memory. When you paste an authorization token, it exists only on your machine's CPU and RAM.

Ready to encode or decode your data?

Transform Base64, URL percent strings, and HTML entities with 100% in-browser privacy and full UTF-8 support.

Open Encoder & Decoder

Frequently Asked Questions

What is the difference between Base64 and Base64URL encoding?
Standard Base64 (RFC 4648 §4) uses characters `+` and `/`, with `=` padding. In URL query parameters or web tokens (such as JSON Web Tokens / JWTs), `+` and `/` cause parsing conflicts because they are reserved URI delimiters. Base64URL (RFC 4648 §5) replaces `+` with `-` and `/` with `_`, and typically omits trailing `=` padding characters.
Why does JavaScript's built-in `btoa()` fail on UTF-8 emojis or non-ASCII characters?
The legacy `window.btoa()` function only accepts binary strings where every character's code point fits within a single byte (0 to 255). Multi-byte unicode characters or Asian scripts occupy 2 to 4 UTF-8 bytes. Passing them to `btoa()` throws an `InvalidCharacterError`. ShiftTools uses modern `TextEncoder` and typed array byte slicing to encode any multi-byte UTF-8 string safely.
What is the difference between `encodeURI()` and `encodeURIComponent()` in JavaScript?
`encodeURI()` is designed to encode a full web address, preserving structural URI delimiters like `:`, `/`, `?`, and `&`. In contrast, `encodeURIComponent()` encodes an individual query string parameter value, converting `:`, `/`, `?`, and `&` into `%3A`, `%2F`, `%3F`, and `%26` so they do not break the outer URL structure.
How does HTML entity encoding prevent Cross-Site Scripting (XSS) attacks?
When user-supplied text contains characters like `<`, `>`, `"`, and `&`, rendering them directly into the DOM allows malicious scripts to execute arbitrary JavaScript. HTML entity encoding transforms `<` into `<` and `>` into `>`, instructing the browser to display them strictly as passive visual glyphs rather than executable markup tokens.
Can ShiftTools decode Base64 data directly into binary downloadable files?
Yes. ShiftTools decodes Base64 data strings directly into binary `Uint8Array` byte buffers and compiles them into local browser `Blob` objects, allowing you to download raw images, audio clips, or PDF documents with zero server mediation.
Are my encoded passwords or authorization tokens kept private?
Yes. All encoding and decoding transformations execute purely within your local browser's JavaScript engine. No tokens, secrets, or payloads are transmitted to backend servers or cached in remote log files.