Base64 Encoding & Decoding: When and How to Use It

ยท 8 min read

What Is Base64 Encoding?

Base64 is a binary-to-text encoding scheme that converts binary data into a string of ASCII characters. It uses 64 characters (A-Z, a-z, 0-9, +, /) plus = for padding. The name "Base64" comes from using a base of 64 distinct characters.

Base64 is not encryption โ€” it provides no security. It's an encoding scheme designed to safely transport binary data through text-only channels like email, URLs, JSON, and HTML. Anyone can decode Base64 instantly.

You encounter Base64 daily: email attachments (MIME), data URLs in HTML/CSS, JWT tokens, API authentication headers, and embedded images in web applications.

๐Ÿ› ๏ธ Encode and decode Base64 instantly

Base64 Encoder/Decoder โ†’ URL Encoder โ†’ JWT Decoder โ†’

How Base64 Works

Base64 converts every 3 bytes (24 bits) of input into 4 characters (6 bits each). Here's the step-by-step process:

Input text: "Hi"
ASCII bytes: 72, 105  (binary: 01001000 01101001)

Step 1: Group into 6-bit chunks
010010 | 000110 | 1001xx

Step 2: Pad to complete the last group
010010 | 000110 | 100100

Step 3: Map to Base64 alphabet
010010 โ†’ S
000110 โ†’ G
100100 โ†’ k

Step 4: Add padding (= for each missing byte)
Result: "SGk="

The Base64 alphabet:

A-Z = 0-25
a-z = 26-51
0-9 = 52-61
+   = 62
/   = 63
=   = padding

Since every 3 input bytes become 4 output characters, Base64 increases data size by approximately 33%. This is the trade-off for safe text transport.

When to Use Base64

Base64 in JavaScript

Browser (btoa/atob)

// Encode string to Base64
const encoded = btoa('Hello, World!');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="

// Decode Base64 to string
const decoded = atob('SGVsbG8sIFdvcmxkIQ==');
console.log(decoded); // "Hello, World!"

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

function decodeUnicode(str) {
  return decodeURIComponent(
    Array.from(atob(str))
      .map(c => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))
      .join('')
  );
}

// Encode file to Base64
async function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result.split(',')[1]);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

Node.js (Buffer)

// Encode
const encoded = Buffer.from('Hello, World!').toString('base64');
// "SGVsbG8sIFdvcmxkIQ=="

// Decode
const decoded = Buffer.from('SGVsbG8sIFdvcmxkIQ==', 'base64').toString('utf-8');
// "Hello, World!"

// Encode file to Base64
const fs = require('fs');
const imageBase64 = fs.readFileSync('image.png').toString('base64');

// Base64URL variant (URL-safe)
const base64url = Buffer.from('data').toString('base64url');
// Uses - and _ instead of + and /

Base64 in Python

import base64

# Encode string
encoded = base64.b64encode(b'Hello, World!').decode('ascii')
print(encoded)  # "SGVsbG8sIFdvcmxkIQ=="

# Decode string
decoded = base64.b64decode('SGVsbG8sIFdvcmxkIQ==').decode('utf-8')
print(decoded)  # "Hello, World!"

# Encode file
with open('image.png', 'rb') as f:
    image_base64 = base64.b64encode(f.read()).decode('ascii')

# Decode to file
image_data = base64.b64decode(image_base64)
with open('output.png', 'wb') as f:
    f.write(image_data)

# URL-safe Base64 (for URLs and filenames)
safe = base64.urlsafe_b64encode(b'data with +/=').decode('ascii')
# Uses - and _ instead of + and /

# Decode URL-safe Base64
original = base64.urlsafe_b64decode(safe)

Base64 on the Command Line

# Encode a string
echo -n "Hello, World!" | base64
# SGVsbG8sIFdvcmxkIQ==

# Decode a string
echo "SGVsbG8sIFdvcmxkIQ==" | base64 --decode
# Hello, World!

# Encode a file
base64 image.png > image.b64

# Decode a file
base64 --decode image.b64 > image_restored.png

# Encode and use in a data URL
echo -n "data:image/png;base64,$(base64 < icon.png)" > data-url.txt

# Decode JWT payload (middle segment)
echo "eyJzdWIiOiIxMjM0NTY3ODkwIn0" | base64 --decode
# {"sub":"1234567890"}

Data URLs & Inline Images

Data URLs let you embed small resources directly in HTML or CSS, eliminating extra HTTP requests:

<!-- Inline image in HTML -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE..." alt="icon">

<!-- Inline in CSS -->
<style>
.icon {
  background-image: url(data:image/svg+xml;base64,PHN2Zy...);
}
</style>

<!-- Inline favicon -->
<link rel="icon" href="data:image/svg+xml;base64,PHN2Zy...">

Use data URLs for small images (under 2-4KB). For larger files, a separate HTTP request with caching is more efficient. Use our Base64 Encoder to quickly convert images to data URLs.

When NOT to Use Base64

Frequently Asked Questions

Is Base64 encoding the same as encryption?

No. Base64 is an encoding scheme, not encryption. It provides no security โ€” anyone can decode Base64 data instantly with our Base64 Decoder. Use actual encryption algorithms (AES, RSA) for protecting sensitive data.

Why does Base64 increase file size by 33%?

Base64 converts every 3 bytes of binary into 4 ASCII characters (6 bits per character instead of 8). So 3 bytes become 4 bytes โ€” a 33% increase. This is the trade-off for safely transporting binary data through text-only channels.

What is Base64URL and how is it different?

Base64URL replaces + with - and / with _ to make encoded strings safe for URLs and filenames without percent-encoding. It also often omits = padding. It's used in JWT tokens and URL parameters.

Can Base64 encode any type of file?

Yes. Base64 can encode any binary data โ€” images, PDFs, executables, archives, anything. It converts raw bytes into ASCII text regardless of the file type.

Related Tools

Base64 Encoder URL Encoder JWT Decoder Hash Generator HTML Entity Encoder