All Articles

Base64 Encoding Under the Hood: UTF-8 Byte Alignment, Padding Traps, and URL-Safe Tokens

Base64 Encoding Under the Hood: UTF-8 Byte Alignment, Padding Traps, and URL-Safe Tokens
Photo: Sendly Team / Unsplash

Almost every developer calls Base64 functions weekly, yet legacy btoa() errors, corrupted multi-byte Unicode characters, and broken URL query parameters still break production APIs. Understanding how Base64 maps 8-bit binary streams into 6-bit printable ASCII characters explains every padding bug and encoding mismatch.

Key Takeaways

TL;DR: Base64 is an encoding scheme (not encryption) that converts every 3 bytes (24 bits) into 4 ASCII characters (6 bits each), adding a 33% size overhead. Always encode strings through TextEncoder UTF-8 bytes before Base64 conversion, and use URL-safe substitution (- and _) for links and JWTs.

1. The 24-Bit Grouping Math: Why Base64 Grows by 33%

Traditional email relays, JSON payloads, and URL query strings were designed for safe ASCII text rather than arbitrary binary bytes (which may contain null bytes, control codes, or delimiter characters). Base64 solves this by regrouping binary bytes into 6-bit chunks because 26 = 64 printable characters (A-Z, a-z, 0-9, +, /).

Because 3 input bytes equal 24 bits, and 24 divides cleanly into four 6-bit groups (4 × 6 = 24), Base64 operates in 3-byte blocks:

ASCII "Man" (3 bytes = 24 bits):
  M (01001101)  a (01100001)  n (01101110)

Regrouped into four 6-bit indices:
  010011 (19 = T)   010110 (22 = W)   000101 (5 = F)   101110 (46 = u)

Result: "TWFu" (4 characters for 3 bytes = +33.3% size overhead)

2. Why Trailing = Padding Exists (And When You Can Strip It)

When your input length is not divisible by 3, the final block lacks enough bits to form four complete 6-bit characters. Base64 pads the remaining bits with zero bits and appends one or two = characters so decoders know the exact byte boundary:

  • 0 remainder bytes (length % 3 === 0): No padding needed.
  • 1 remainder byte (8 bits): Produces 2 Base64 characters (12 bits, 4 trailing zeros) plus == padding.
  • 2 remainder bytes (16 bits): Produces 3 Base64 characters (18 bits, 2 trailing zeros) plus = padding.

In protocols like JWT and OAuth URLs, trailing = characters are commonly omitted because the payload byte count is unambiguous from character length modulo 4 (except length % 4 === 1, which is mathematically impossible in valid Base64).

3. The Classic JavaScript btoa() Unicode Trap

Many web applications crash in production when calling native window.btoa("Sendly 🚀") directly. That happens because btoa() expects single-byte Latin-1 characters (code points 0x00–0xFF), whereas modern international scripts, accented characters, and emojis span multi-byte UTF-16 code units.

The clean RFC-compliant solution is converting text into raw UTF-8 bytes via TextEncoder first, encoding those bytes safely in chunks, and decoding back with TextDecoder:

const utf8Bytes = new TextEncoder().encode(inputText);
const base64 = bytesToBase64(utf8Bytes); // Safe for global scripts & emojis

4. Standard Base64 vs. URL-Safe Base64 (RFC 4648 §5)

Feature Standard Base64 URL-Safe Base64 (Base64Url)
62nd & 63rd Characters + and / - (minus) and _ (underscore)
URL Query Safety Requires percent-encoding (%2B, %2F) Safe unescaped in paths, cookies & JWTs
Padding Behavior Usually includes = or == Often omitted (replace(/=+$/, ''))

5. Remember: Base64 Is Transport Formatting, Never Confidentiality

Never treat Base64 strings as hidden secrets. Anyone can reverse a Base64 blob instantaneously without a key. If you need true payload confidentiality alongside portable encoding, encrypt payload bytes first (such as browser-side AES-256-CBC) and test UTF-8 or URL-safe Base64 conversions locally with zero server logging using Sendly's Base64 Encoder & Decoder.

Privacy-First Browser Suite

Try Sendly tools with zero sign-up

Transfer files peer-to-peer, sync collaborative notes live, or share your screen straight from any browser tab.

Open P2P TransferLive NotepadScreen Share

Continue Reading

Browse all articles
Measuring Password Strength Properly: Shannon Entropy, CSPRNG vs. Math.random(), and 6-Word Diceware
Cryptography6 min read

Measuring Password Strength Properly: Shannon Entropy, CSPRNG vs. Math.random(), and 6-Word Diceware

JWT Security Pitfalls: Why "alg: none", Weak Secrets, and Public Token Debuggers Put APIs at Risk
Security4 min read

JWT Security Pitfalls: Why "alg: none", Weak Secrets, and Public Token Debuggers Put APIs at Risk

PREVIOUS ARTICLEPREVIOUS
JWT Security Pitfalls: Why "alg: none", Weak Secrets, and Public Token Debuggers Put APIs at Risk

JSON Web Tokens (JWTs) power authentication across modern microservices, single-page apps, and mobile APIs. Yet one careless verification setting—or pasting a l...

NEXT ARTICLENEXT
SSRF Attacks and URL Sandboxing: How Modern Web Extractors Safely Fetch Untrusted Links

Every time an application accepts a user-supplied URL—whether to render a link preview, fetch Markdown for an AI agent, or inspect redirects—it opens a potentia...