ToolifyHub.tools
Skip to main content

Base64 Encoder & Decoder

Direct Answer & Definition

Base64 Encoder & Decoder converts text, binary files, and images into Base64 ASCII strings (RFC 4648) and vice versa. Use the interactive text tabs, upload files up to 2MB, or paste images directly using Ctrl+V to generate Data URLs, HTML img tags, and CSS background rules. 100% free and client-side.

Securely encode and decode text, files, and images to Base64 format directly in your browser.

Last Updated: July 2026|Reviewed by: ToolifyHub.tools Editorial Team|100% Browser-Based Security
IETF RFC 4648 & W3C RFC 2397 specification compliant100% Client-Side Engine — zero server uploads, 100% privateLast reviewed: July 2026Developer Reference for APIs, Web & Security

Convert plain text, images, and binary files to Base64 format or decode strings back to raw data. Features Ctrl+V clipboard image paste, Data URL generator, processing time metrics, and multi-format exports.

🔤 Text & UTF-8 Support🖼️ Image Ctrl+V Paste📁 File to Base64 (2MB)⚡ Instant Data URL🔒 100% Client-Side
0 Characters

Pro Tip

Base64 encoding increases file sizes by approximately 33%. Always use Base64 for small layout icons, inline SVGs, or tiny images to avoid rendering roundtrip latency, but keep larger media assets in standard binary formats (JPG, PNG) for speed optimization.

Real World Uses

  • Inline styling optimization (avoiding extra HTTP image requests).
  • Encoding complex parameter keys safely inside URL strings.
  • Transmitting raw binary database items inside pure JSON REST responses.

UTF-8 Multi-Byte Edge Cases

JavaScript btoa() only accepts Latin1. Emojis, accents, CJK require explicit UTF-8 handling.

btoa() Limitation

JavaScript native btoa() only accepts Latin1 (8-bit). Throws InvalidCharacterError on emojis/accents. Must use TextEncoder + btoa for UTF-8.

UTF-8 Safe Encode

btoa(unescape(encodeURIComponent(str))) → converts UTF-8 to %XX then to binary. Decode: decodeURIComponent(escape(atob(encoded))).

Multi-Byte Example

"🌍" = 4 bytes (F0 9F 8C 8D) → 6 Base64 chars (8J+QgA==). ASCII char = 1 byte → 1-2 Base64 chars.

Base64URL Deep-Dive — JWT Token Anatomy

JWT Token Anatomy

Header.Payload.Signature — each part Base64URL encoded. Header: {"alg":"HS256","typ":"JWT"}. Payload: claims (sub, exp, iat). Signature: HMAC-SHA256.

URL-Safe Alphabet

Base64: + / = → Base64URL: - _ (padding omitted). No URL encoding needed for query params, cookies, JWT.

Padding Omission

Base64URL often drops = padding. Decoder must handle missing padding: append = until length % 4 === 0.

MIME Multipart Structure & Line Length Limits

MIME Multipart

Content-Type: multipart/mixed; boundary=XYZ. Each part has headers + Base64 body. Used for email attachments.

Part Structure

Each part: Content-Type, Content-Transfer-Encoding: base64, Content-Disposition, blank line, Base64 data.

Line Length Limit

MIME (RFC 2045) requires max 76 chars per line. Insert CRLF every 76 chars. Our tool outputs continuous by default.

Encoding Detection Heuristics

Is It Base64? Heuristics

1) Length % 4 === 0 (or 2/3 with padding). 2) Chars only A-Z,a-z,0-9,+,/,=. 3) = only at end (0-2). 4) No whitespace (unless MIME).

False Positives

Short strings ("SGVsbG8") may match by chance. Longer strings (>20 chars) with valid charset = high confidence.

Programmatic Check

try { atob(str); return true; } catch { return false; } — but catches false positives. Add regex /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.

Streaming / Large File Encoding Strategies

Streaming Large Files

FileReader.readAsDataURL loads entire file to memory. For >100MB, use File.slice() + readAsArrayBuffer + incremental Base64 chunks.

Web Workers

Offload encode/decode to Web Worker to keep main thread responsive. Use postMessage with transferable ArrayBuffers.

Chunk Size

Process in 3-byte aligned chunks (3KB, 30KB, 300KB) to avoid partial chunk padding overhead at chunk boundaries.

Binary vs Text Mode — Critical Distinction

Text Mode (btoa)

Input: UTF-8 string → bytes → Base64. Use for JSON, XML, CSV, source code. Handles Unicode via TextEncoder.

Binary Mode (FileReader)

Input: raw bytes (ArrayBuffer/Blob) → Base64. Use for images, PDFs, ZIPs, executables. Preserves exact byte values.

Corruption Risk

Passing binary data through btoa() without TextEncoder corrupts bytes >127. Always use FileReader.readAsArrayBuffer for binary.

Performance Benchmarks — Throughput Targets

Browser Native (btoa/atob)

~100-500 MB/s encode/decode in V8. Highly optimized C++ implementation. Best for strings <10MB.

FileReader (async)

~50-200 MB/s including I/O overhead. Limited by event loop. Use Web Worker for sustained throughput.

Wasm / SIMD

Custom Wasm Base64 can reach 1-2 GB/s using SIMD (v128). Use for real-time video/audio streaming encoding.

Base64 Alternatives — Base58, Base32, Ascii85

Base58 (Bitcoin)

Alphabet: 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz. No 0,O,I,l. Used for Bitcoin addresses, IPFS. No padding.

Base32 (RFC 4648)

Alphabet: A-Z, 2-7. Case-insensitive. 40% overhead. Used for TOTP secrets, DNS, file systems. Padding =.

Ascii85 / Base85

4 bytes → 5 chars (25% overhead). Alphabet: !-u. Used in PDF, Git, PostScript. More compact than Base64.

Line Length Limits — MIME 76 Chars, PEM 64 Chars

MIME 76-Char Limit

RFC 2045: encoded lines MUST NOT exceed 76 chars. Insert CRLF. Our tool outputs single-line; add .match(/.{1,76}/g).join('\n') for MIME.

PEM Format

-----BEGIN CERTIFICATE----- + 64-char lines + -----END CERTIFICATE-----. Standard for X.509 certs, SSH keys.

No Limit (Data URLs)

Data URLs (RFC 2397) have no line length requirement. Single-line Base64 preferred for CSS/HTML embedding.

What Is Base64 Encoding & Why Does It Exist?

Base64 is a binary-to-text encoding scheme standardized by the Internet Engineering Task Force (IETF RFC 4648). It translates arbitrary 8-bit binary data (bytes) into a restricted set of 64 printable ASCII characters.

Early network communication protocols (such as SMTP email servers and early HTTP gateways) were designed strictly to handle 7-bit ASCII text. If raw 8-bit binary files (like PNG images, ZIP archives, or PDFs) were transmitted directly over these systems, certain byte sequences (like control characters or null bytes) would be misinterpreted or truncated by legacy routers, corrupting the file. Base64 solved this by guaranteeing that binary data is represented using only safe, universal text characters.

Index RangeBase64 Characters6-Bit Binary RangeDescription
0–25A – Z000000 – 011001Uppercase Latin Letters (26 values)
26–51a – z011010 – 110011Lowercase Latin Letters (26 values)
52–610 – 9110100 – 111101Numeric Digits (10 values)
62+ (Plus)111110Standard Base64 Symbol (+ in Standard, - in Base64URL)
63/ (Slash)111111Standard Base64 Symbol (/ in Standard, _ in Base64URL)
Padding= (Equals)N/APadding character appended when byte count is not divisible by 3

Step-by-Step Mathematical Encoding & Padding Rules

Base64 operates by taking groups of 3 input bytes (24 bits) and re-grouping them into 4 6-bit index numbers. Each 6-bit number (0 to 63) maps directly to one character in the Base64 alphabet:

Worked Example: Encoding the ASCII text "Man"

1. Input Characters: "M", "a", "n"

2. ASCII Decimals: 77, 97, 110

3. 8-Bit Binary Stream (24 bits total):

01001101 01100001 01101110

4. Re-group into 4 6-bit Chunks:

010011 | 010110 | 000101 | 101110

5. Convert 6-bit Chunks to Decimals: 19, 22, 5, 46

6. Map to Base64 Alphabet: "TWFu"

Why Does Base64 Use Padding (= or ==)?

Base64 requires data to process in complete 24-bit (3-byte) blocks. When your input text or binary file length is not a multiple of 3 bytes, padding bits and equal signs (=) are appended to complete the final 4-character block:

Input: "Ma" (2 Bytes / 16 Bits)

Needs 2 zero-padding bits to form three 6-bit chunks (18 bits). The missing 4th chunk is replaced with one equals sign.

Output: "TWE="

Input: "M" (1 Byte / 8 Bits)

Needs 4 zero-padding bits to form two 6-bit chunks (12 bits). The missing 3rd and 4th chunks are replaced with two equals signs.

Output: "TQ=="

Base64 vs Base64URL vs Hex vs URL Encoding vs Hashing

FormatCharacter SetOverheadURL Safe?Primary Purpose
Base64 (Standard)A-Z, a-z, 0-9, +, /+33.3%No (+ and / need encoding)Binary data in 7-bit clean text streams (MIME, Data URLs)
Base64URLA-Z, a-z, 0-9, -, _+33.3%Yes (URL query safe)JWT tokens, OAuth state parameters, web API endpoints
Hexadecimal (Base16)0-9, a-f (16 chars)+100.0%YesCryptographic hashes (MD5, SHA-256), color codes, byte inspection
URL / Percent Encoding%XX hex tripletsVariable (up to +200%)YesEscaping non-ASCII characters in URL query strings
AES EncryptionRaw binary / Base64 wrappedVariable + IV/TagDepends on wrapperConfidentiality (requires secret key to decrypt)
SHA-256 Hashing64 hex charactersFixed 256 bitsYesOne-way cryptographic integrity verification

Real-World Engineering Use Cases & Code Snippets

🖼️ CSS & HTML Data URIs

Embed small icons directly inside CSS stylesheets to eliminate HTTP request roundtrips.

background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0...");

🔑 JSON Web Tokens (JWT)

JWT headers and payloads use Base64URL to pass structured claims in HTTP Auth headers.

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

📧 Email MIME Attachments

SMTP protocols encode PDF, DOCX, and image attachments into Base64 ASCII text streams.

Content-Type: application/pdf Content-Transfer-Encoding: base64 JVBERi0xLj...

🌐 REST API & GraphQL Payloads

Transmit raw binary files or profile avatars inside standard JSON payloads.

{ "avatar": "data:image/png;base64,iVBORw0KGgoAAAAN..." }

Security Myths — Why Base64 Is NOT Encryption

CRITICAL SECURITY WARNING: Base64 is an encoding format, not an encryption algorithm. It provides ZERO confidentiality, ZERO secrecy, and ZERO data protection.

❌ Dangerous Unsafe Practices

  • Storing user passwords as Base64 in database tables
  • Encoding API keys or secret tokens in frontend JavaScript
  • Assuming Base64 masks credit card data from network sniffers
  • Using Base64 to bypass security filters or malware scanners

✅ Legitimate Safe Practices

  • Embedding small UI icons directly in CSS or HTML Data URIs
  • Transmitting binary images within JSON web API requests
  • Passing signed JWT claims in HTTP Authorization headers
  • Encoding 8-bit binary attachments for 7-bit email SMTP servers

Ref: OWASP Input Validation & Encoding Guidelines →

Performance Overhead — The 33% Size Increase Factor

Because Base64 translates 3 raw binary bytes into 4 ASCII text characters, the output size is mathematically 33.3% larger than the original input file. For example:

Original PNG Image

100 KB

Base64 Output Size

133.3 KB (+33%)

Data URI Header Added

~133.4 KB

Web Performance Tip: Base64 Data URIs bypass HTTP request latency, making them great for tiny UI icons (< 2KB). However, embedding large photos or PDFs as Base64 in HTML/CSS blocks browser parallel downloading and inflates DOM parse time. For larger media, use standard WebP files served via HTTP/2 or HTTP/3 CDN links.

Multi-Language Developer Code Reference

How to encode and decode Base64 strings across popular programming languages:

JavaScript (Browser)

// Encodeconst encoded = btoa(unescape(encodeURIComponent("Hello World 🌍")));
// Decodeconst decoded = decodeURIComponent(escape(atob(encoded)));

Node.js (Server)

// Encodeconst encoded = Buffer.from("Hello World", "utf-8").toString("base64");
// Decodeconst decoded = Buffer.from(encoded, "base64").toString("utf-8");

Python 3

// Encodeimport base64 encoded = base64.b64encode(b"Hello World").decode("utf-8")
// Decodedecoded = base64.b64decode(encoded).decode("utf-8")

Go (Golang)

// Encodeimport "encoding/base64" encoded := base64.StdEncoding.EncodeToString([]byte("Hello World"))
// DecodedecodedBytes, _ := base64.StdEncoding.DecodeString(encoded)

PHP

// Encode$encoded = base64_encode("Hello World");
// Decode$decoded = base64_decode($encoded);

Java (java.util.Base64)

// EncodeString encoded = Base64.getEncoder().encodeToString("Hello World".getBytes(StandardCharsets.UTF_8));
// Decodebyte[] decoded = Base64.getDecoder().decode(encoded);

C# (.NET)

// Encodestring encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes("Hello World"));
// Decodebyte[] bytes = Convert.FromBase64String(encoded);

Common Base64 Errors & Troubleshooting Guide

InvalidCharacterError in JS

Cause: Passing Unicode characters or emojis directly to btoa().

Fix: Use encodeURIComponent before btoa(): btoa(unescape(encodeURIComponent(str))).

Corrupted Decoded Output

Cause: Copying extra whitespace, newlines, or HTML tags into the string.

Fix: Trim all whitespace and strip Data URL headers before decoding raw binary bytes.

Broken Base64 Image Render

Cause: Missing the Data URL prefix (e.g. data:image/png;base64,).

Fix: Ensure the MIME header matches the exact image format (png, jpeg, webp, svg+xml).

Why You Actually Need a Base64 Encoder & Decoder

The Base64 Encoder & Decoder converts raw text, binary assets, and images into Base64 ASCII strings and vice versa.

Whether you are embedding inline SVG graphics, formatting JSON REST payloads, inspecting JWT claims, or troubleshooting email MIME attachments, this tool executes all encoding operations 100% locally in your browser memory.

Why Use ToolifyHub.tools?

Our sandbox design enables safe local execution, removing the threat of third-party data collection inherent to typical online tools.

🔒 100% Privacy-First Sandbox

This tool runs entirely inside your browser. No files or inputs are sent to any external server.

❌ No Sign-Up or Accounts

Enjoy instant, anonymous access to all features without sharing email or credentials.

⚡ High-Speed Local Rendering

Optimized client-side rendering ensures near-zero processing wait times.

🎁 Free Forever with Zero Caps

Supported exclusively by simple display advertisements, keeping premium tools accessible to everyone.

🎯 Best For:Developers, students, office managers, and freelancers needing private document/calculation tasks.
💡 When to Use:Choose this when processing sensitive data, private text, spreadsheets, or images that should not sit in cloud databases.
🔑 Key Takeaway:Immediate browser execution guarantees zero storage leak vectors. A fast, clean, desktop alternative.

How to Use the Base64 Encoder & Decoder on ToolifyHub.tools

  1. 1

    Select Text, File, or Image Mode

    Switch between the Text editor, File upload (up to 2MB), or Image converter tabs at the top of the form.

  2. 2

    Choose Encode or Decode Mode

    Toggle between Encode mode (translating raw input to Base64) and Decode mode (converting a Base64 string back to readable text or a binary file).

  3. 3

    Input Data or Paste Image (Ctrl+V)

    Type or paste your string into the input area. On the Image tab, press Ctrl+V to paste any image snippet directly from your clipboard.

  4. 4

    Inspect Real-Time Metrics & Preview

    View output character count, processing time (ms), and reconstructed image previews automatically.

  5. 5

    Copy or Download Output

    Copy Data URLs, HTML img tags, CSS background rules, or download the converted result as a .txt file.

Real-World Scenarios Where This Saves You

🎯

📧 Embedding Newsletter Images Offline

A marketing designer embeds small PNG icons directly into an HTML newsletter using Base64 Data URIs so the graphics display even when email clients block external remote images.

💼

🔑 Inspecting Base64URL JWT Tokens

A backend engineer decodes a JWT authorization header string into readable JSON to verify token claims and expiration timestamps during API debugging.

🚀

🖼️ Storing Thumbnail Assets in LocalStorage

A web app developer converts user avatar icons into Base64 Data URIs to store them in browser LocalStorage for instant offline loading.

Common Mistakes to Avoid

Confusing Base64 encoding with encryption: Base64 provides zero security or confidentiality. Anyone can decode it in milliseconds. Never use it to store passwords or secret keys.
Using Base64 for large media files (> 50KB): Base64 increases file size by 33%, inflates HTML/CSS file size, and blocks parallel browser HTTP asset downloading.
Passing UTF-8 emojis directly into JavaScript btoa(): btoa() throws an InvalidCharacterError on Unicode. Always run encodeURIComponent() before btoa() in web browsers.
Forgetting the Data URL header prefix for HTML images: Browsers require data:image/png;base64, before the Base64 string to render inline images properly.
Copying extra trailing whitespace or newlines: Including trailing spaces or line breaks when copying Base64 strings can corrupt binary decoding.
Using standard Base64 (+ and /) in URL query parameters: Plus (+) and slash (/) characters break HTTP URLs. Use Base64URL (- and _) for URL query parameters.
Assuming Base64 hides data from web crawlers or security scanners: Antivirus scanners and web crawlers automatically decode Base64 strings during automated security checks.
Manual string manipulation instead of browser FileReader APIs: Use FileReader.readAsDataURL() for clean, error-free binary file conversions.

How We Tested This Tool

To guarantee complete accuracy and reliability, our engineering and QA team validates the Base64 Encoder & Decoder regularly against:

  • Cross-Browser Compatibility: Verified on standard releases of Google Chrome, Apple Safari, Mozilla Firefox, and Microsoft Edge.
  • Responsive Viewports: Tested for mobile, tablet, and desktop dimensions to ensure layout responsiveness.
  • Input Assertions: Subjected to multiple normal, extreme, and empty parameters to prevent script failure and guarantee output correctness.

Local Browser Sandbox vs. Cloud Tools

MetricToolifyHub SandboxTypical Cloud Services
File Upload RisksNone (0% upload rate)High (transmits data to remote servers)
Execution CostFree forever (No limits)Subscription-gated or limits applied
Data Retention PolicyImmediate deletion on page closeRetained in cloud buckets or server logs
Processing LatencySub-second client executionNetwork upload & queuing delays

Authoritative Specifications & Documentation

Frequently Asked Questions

It is used to convert binary files or non-ASCII characters into safe 7-bit ASCII text, allowing inline embedding of small images or fonts directly in HTML/CSS.
No, all encoding and decoding operations execute locally on your device inside your web browser. Your data is never uploaded.
Base64 represents 3 binary bytes using 4 text characters, which increases total output size by approximately 33.3%.
Non-Base64 characters or invalid padding will disrupt the decoding algorithm, throwing a parsing error or producing corrupted output.
Yes. Pasting a Base64 file string into the decoder allows you to reconstruct and download the original binary image, PDF, or text file.

Privacy & Security Disclaimer: This Base64 Encoder & Decoder executes 100% locally in your client web browser using standard Web APIs (btoa, atob, and FileReader). No text, images, or uploaded binary files are transmitted to or stored on any server. Base64 is an encoding format (IETF RFC 4648) and does not provide encryption or data security. Last reviewed: July 2026.

Related Tools & Workflows

Format encoded JSON, Hash encoded data, Encode URLs after Base64, Encode extracted text to Base64

Discover More Tools