惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
月光博客
月光博客
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
人人都是产品经理
人人都是产品经理
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
有赞技术团队
有赞技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - Franky
The Cloudflare Blog
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
Jina AI
Jina AI
阮一峰的网络日志
阮一峰的网络日志
小众软件
小众软件
Last Week in AI
Last Week in AI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Base64 Encoding Explained — JWT Tokens, Data URIs, and Ku...
Code Wiz Tools · 2026-06-26 · via DEV Community

You have probably copied a Base64 string a hundred times without thinking about it. That long chain of letters and slashes at the end of a JWT. The data:image/png;base64, blob in a CSS file. The Authorization: Basic header in a Postman collection.

Base64 is everywhere in a developer's daily work — and most developers have a fuzzy mental model of what it actually does. This article clears that up, and covers the five real production use cases where you will encounter it.


What is Base64 and why does it exist?

Base64 converts binary data into a string of 64 printable ASCII characters: the letters A–Z and a–z, digits 0–9, plus + and /. The name literally describes the alphabet size.

The reason it exists: many systems that move data were designed for text only. Email protocols (SMTP), HTML attributes, JSON payloads, XML documents, HTTP headers — all of these were built around the assumption that data is readable ASCII text. Raw binary bytes can corrupt or break these systems.

Base64 solves this by guaranteeing that whatever you encode will contain only characters that transmit safely through any text-based system.

The size tradeoff

Base64 encodes every 3 bytes of input into 4 output characters. That means encoded output is always approximately 33% larger than the original data. This is the price of universality.

The = or == at the end of a Base64 string is padding — added when the input length is not divisible by 3. One = means one byte of padding was needed; == means two bytes. Never strip padding manually — it is part of the RFC 4648 standard and removing it breaks decoding.


Base64 is NOT encryption

This is the most important thing to understand, and it gets confused constantly.

Base64 is encoding, not encryption. Anyone can decode it instantly with zero key or password. There is nothing protecting the data — it is just a different representation.

// This is NOT secure
const "secret" = btoa("admin:password123");
// Result: YWRtaW46cGFzc3dvcmQxMjM=
// Anyone can run atob("YWRtaW46cGFzc3dvcmQxMjM=") and read it

// This is what it looks like in an HTTP Basic Auth header
// Authorization: Basic YWRtaW46cGFzc3dvcmQxMjM=
// The credentials are completely readable — this is just transport formatting

Never store passwords, API secrets, or private tokens as Base64 and assume they are secure. Use proper encryption (AES-256, bcrypt, Argon2) when you need actual protection.


The 5 places you will encounter Base64 in production

1. JWT Tokens

A JWT (JSON Web Token) has three Base64URL-encoded parts separated by dots:

eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiYWxpY2UifQ.abc123sig
     ^header                  ^payload              ^signature

The header and payload are Base64URL encoded — not standard Base64. Base64URL is a URL-safe variant that replaces + with - and / with _ to avoid issues in URLs and HTTP headers.

To read a JWT payload without a library:

  1. Take the middle section (between the two dots)
  2. Replace all - with +
  3. Replace all _ with /
  4. Decode from Base64
function decodeJwtPayload(token) {
  const payload = token.split('.')[1];
  // Convert Base64URL to standard Base64
  const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
  return JSON.parse(atob(base64));
}

// Usage
const token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiYWxpY2UiLCJleHAiOjE3MjAwMDAwMDB9.sig";
console.log(decodeJwtPayload(token));
// → { user: "alice", exp: 1720000000 }

You can also use the Base64 decoder on CodeWizTools to decode JWT payloads manually — paste the middle section and the tool decodes it to readable JSON.

Note: Never verify a JWT by just decoding the payload. Always verify the signature server-side. Client-side JWT decoding is fine for reading claims (user ID, role, expiry) — but never trust unverified claims for authorization decisions.


2. HTTP Basic Authentication

HTTP Basic Auth sends credentials in the Authorization header as Base64-encoded username:password:

Authorization: Basic YWRtaW46cGFzc3dvcmQxMjM=

Decoded: admin:password123

This is the standard format for API basic auth. Most REST clients (Postman, curl, Insomnia) handle this automatically, but knowing the encoding format helps when you are debugging raw HTTP requests or writing test scripts.

# curl with Basic Auth — curl encodes this for you
curl -u admin:password123 https://api.example.com/data

# Equivalent with manual header
curl -H "Authorization: Basic YWRtaW46cGFzc3dvcmQxMjM=" https://api.example.com/data


3. Data URIs — Embedding Images in HTML and CSS

A data URI lets you embed a file directly into HTML or CSS without a separate HTTP request:

<!-- Standard image tag with external URL -->
<img src="https://example.com/icon.png" alt="Icon">

<!-- Same icon embedded as Base64 data URI — no HTTP request needed -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=" alt="Icon">

The format is:

data:[media type];base64,[Base64 encoded data]

When to use data URIs:

  • Small icons (under 2–3 KB) that are critical for above-the-fold rendering
  • Email templates — external images are often blocked by email clients
  • Canvas-generated images you want to save or display

When NOT to use them:

  • Images over ~5 KB — the 33% size overhead becomes significant
  • Images used on multiple pages — they cannot be cached separately
  • Lazy-loaded content — data URIs cannot be lazy loaded

4. Kubernetes Secrets

Every value in a Kubernetes Secret manifest must be Base64-encoded:

apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
type: Opaque
data:
  username: YWRtaW4=          # base64 of "admin"
  password: cGFzc3dvcmQxMjM=  # base64 of "password123"

This is a common point of confusion for developers new to Kubernetes — it looks like the credentials are protected, but Base64 is just encoding, not encryption. Kubernetes Secrets are not inherently secure; you need additional tooling (Sealed Secrets, HashiCorp Vault, AWS Secrets Manager) for real secret management.

# Encoding a secret value for a Kubernetes manifest
echo -n "password123" | base64
# Output: cGFzc3dvcmQxMjM=

# The -n flag is important — without it, echo adds a newline
# which gets encoded and causes authentication failures


5. Sending Binary Files in JSON APIs

REST APIs that use JSON cannot transmit raw binary data (images, PDFs, audio files) directly. Base64 is the standard workaround:

{
  "filename": "report.pdf",
  "content_type": "application/pdf",
  "data": "JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3Ro..."
}

This pattern is used in email APIs (SendGrid, Mailgun), document processing APIs, and any API that needs to receive or send files over a JSON interface.


The Unicode problem — why most Base64 tools break

The browser's built-in btoa() function only handles ASCII. Try encoding text with non-ASCII characters and you will get an error:

btoa("اردو");
// → Uncaught DOMException: The string to be encoded 
//   contains characters outside of the Latin1 range.

btoa("😀");
// → Same error

The correct way to encode Unicode text to Base64 in JavaScript:

// WRONG — breaks on any non-ASCII character
const broken = btoa(text);

// CORRECT — handles full Unicode (Arabic, Urdu, Chinese, emoji)
function encodeBase64Unicode(str) {
  const bytes = new TextEncoder().encode(str);
  let binary = '';
  bytes.forEach(byte => binary += String.fromCharCode(byte));
  return btoa(binary);
}

function decodeBase64Unicode(base64) {
  const binary = atob(base64);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }
  return new TextDecoder().decode(bytes);
}

// Now these work
encodeBase64Unicode("اردو");     // → "2KfYsdm/2Yg="
encodeBase64Unicode("😀");      // → "8J+YgA=="
encodeBase64Unicode("中文");     // → "5Lit5paH"

TextEncoder converts the string to UTF-8 bytes first, then btoa encodes those bytes. TextDecoder reverses the process. This is the correct standard per RFC 4648 and is what major frameworks and APIs use.

The older pattern btoa(unescape(encodeURIComponent(str))) also works but uses the deprecated unescape() function — avoid it in new code.


Base64 vs Base64URL — which one is it?

Standard Base64 uses + and / in its alphabet. These characters have special meaning in URLs (+ = space in query strings, / = path separator), which causes problems when Base64 strings appear in URLs or HTTP headers.

Base64URL solves this by substituting:

  • +-
  • /_

And optionally omitting the = padding.

Context Format Characters
JWT tokens Base64URL A–Z, a–z, 0–9, -, _
Kubernetes secrets Standard Base64 A–Z, a–z, 0–9, +, /
Data URIs Standard Base64 A–Z, a–z, 0–9, +, /
HTTP Basic Auth Standard Base64 A–Z, a–z, 0–9, +, /
OAuth 2.0 PKCE Base64URL A–Z, a–z, 0–9, -, _

If you see - and _ in a Base64-looking string, it is Base64URL (almost certainly a JWT).


Quick reference

// Standard encode/decode (ASCII only — breaks on Unicode)
btoa("hello")          // → "aGVsbG8="
atob("aGVsbG8=")       // → "hello"

// Unicode-safe encode/decode (use this in production)
encodeBase64Unicode("اردو")   // → "2KfYsdm/2Yg="
decodeBase64Unicode("2KfYsdm/2Yg=")  // → "اردو"

// Decode a JWT payload (read-only — does not verify signature)
decodeJwtPayload("eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiYWxpY2UifQ.sig")
// → { user: "alice" }

// Encode for Kubernetes secret (CLI)
echo -n "my-secret-value" | base64


Tool

For quick encoding and decoding without writing code — I built a free Base64 Encoder & Decoder that handles full Unicode correctly (Arabic, Urdu, Chinese, emoji), supports JWT payload decoding, and runs 100% in the browser with no data sent to any server. Useful for inspecting JWT tokens during API development, preparing Kubernetes secret values, and debugging Base64 encoding issues.


Summary

  • Base64 converts binary data to printable ASCII text — not encryption
  • It appears in JWT tokens (Base64URL variant), HTTP auth, data URIs, Kubernetes secrets, and JSON file APIs
  • Standard btoa() breaks on Unicode — use TextEncoder + btoa instead
  • Base64URL uses - and _ instead of + and / — look for it in JWTs and OAuth
  • Encoded output is ~33% larger than input — factor this in for data URIs and API payloads

Building something with CodeWizTools? Check out the full collection of free browser-based utilities at codewiztools.com — JSON formatter, URL encoder, RGBA color picker, Lorem Ipsum generator, and more.