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
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
- Email attachments: SMTP was designed for 7-bit ASCII text. Base64 encodes binary attachments (images, PDFs) so they can travel through email systems.
- Data URLs: Embed small images directly in HTML/CSS as
data:image/png;base64,...to reduce HTTP requests. - JWT tokens: JWT header and payload are Base64URL-encoded JSON. Use our JWT Decoder to inspect them.
- HTTP Basic Authentication: Credentials are Base64-encoded in the
Authorization: Basicheader. - Binary data in JSON: JSON doesn't support binary. Encode binary data as Base64 strings for API transport.
- URL-safe data: Base64URL variant (replacing +/ with -_) safely encodes data for URLs without percent-encoding.
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
- Not for encryption. Base64 provides zero security. Anyone can decode it instantly. Use AES or other encryption for sensitive data, and use our Hash Generator for creating checksums.
- Not for large files. The 33% size increase is significant for large files. A 10MB image becomes ~13.3MB as Base64.
- Not for images in production. Inline Base64 images can't be cached by browsers. Use regular
<img>tags with proper caching headers for production sites. - Not for passwords. Never "encode" passwords with Base64. Use proper hashing algorithms (bcrypt, argon2) for password storage.
- Not when you have binary transport. If your protocol supports binary (WebSocket binary frames, HTTP/2, gRPC), send binary directly โ don't Base64-encode it.
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.