PureTools

Base64 Encoding: What It Is and How to Use It

PureTools Team· 7 min read
Base64 Encoding: What It Is and How to Use It

Base64: Not Encryption, Not Compression

Base64 is the most misunderstood encoding in web development. It's not encryption (anyone can decode it). It's not compression (it makes data 33% larger). So what is it?

The Problem Base64 Solves

Some systems only handle text — email (SMTP), JSON, URLs, HTML attributes. Binary data (images, PDFs, executables) can contain bytes that break these text-based systems. Base64 converts any binary data into a safe set of 64 ASCII characters: A-Z, a-z, 0-9, +, /, and = for padding.

How It Works

Every 3 bytes of input become 4 Base64 characters:

Input:  M        a        n
ASCII:  77       97       110
Binary: 01001101 01100001 01101110

Split into 6-bit groups:
010011 010110 000101 101110

Map to Base64 alphabet:
   T      W      F      u

Result: "TWFu"

This is why Base64 output is always ~33% larger than the input — you're encoding 3 bytes into 4 characters.

In JavaScript

// Encode
btoa('Hello, World!')  // "SGVsbG8sIFdvcmxkIQ=="

// Decode
atob('SGVsbG8sIFdvcmxkIQ==')  // "Hello, World!"

// For Unicode (btoa only handles Latin-1):
function encodeUnicode(str) {
  return btoa(encodeURIComponent(str).replace(
    /%([0-9A-F]{2})/g,
    (_, p1) => String.fromCharCode(parseInt(p1, 16))
  ));
}

Common Uses

  • Data URIs: <img src="data:image/png;base64,iVBOR..."> — embed small images directly in HTML/CSS
  • HTTP Basic Auth: Authorization: Basic dXNlcjpwYXNz (that's user:pass)
  • JWT tokens: The header and payload are Base64url-encoded JSON
  • Email attachments: MIME uses Base64 for binary attachments

When NOT to Use Base64

  • Images on the web: A 50KB image becomes 67KB in Base64, and the browser can't cache it separately. Use regular <img src> for anything over ~2KB.
  • "Hiding" data: Base64 is not encryption. Anyone can decode it. Don't Base64-encode passwords or secrets thinking they're protected.
  • Large files: The 33% size overhead is significant for large payloads.

Base64url

Standard Base64 uses + and /, which are special in URLs. Base64url replaces them with - and _, and drops the = padding. This is what JWTs use.

Encode/decode now: Base64 Encoder/Decoder — paste any text, get instant Base64 output.