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

推荐订阅源

S
Security @ Cisco Blogs
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tenable Blog
C
CERT Recently Published Vulnerability Notes
T
Threatpost
C
Cisco Blogs
Know Your Adversary
Know Your Adversary
T
Tor Project blog
博客园 - 司徒正美
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
宝玉的分享
宝玉的分享
博客园 - 三生石上(FineUI控件)
L
LangChain Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Stack Overflow Blog
Stack Overflow Blog
Microsoft Security Blog
Microsoft Security Blog
AWS News Blog
AWS News Blog
人人都是产品经理
人人都是产品经理
P
Proofpoint News Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
A
Arctic Wolf
L
LINUX DO - 热门话题
C
Cyber Attacks, Cyber Crime and Cyber Security
爱范儿
爱范儿
美团技术团队
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
PCI Perspectives
PCI Perspectives
H
Heimdal Security Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
F
Full Disclosure
SecWiki News
SecWiki News
T
The Blog of Author Tim Ferriss
Help Net Security
Help Net Security
Google DeepMind News
Google DeepMind News
P
Palo Alto Networks Blog
博客园 - 叶小钗
C
Check Point Blog
Scott Helme
Scott Helme
V
Visual Studio Blog
博客园 - 聂微东
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google Online Security Blog
Google Online Security Blog
大猫的无限游戏
大猫的无限游戏
The Register - Security
The Register - Security

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Base64 Encoding Explained — JWT Tokens, Data URIs, and Kubernetes Secrets
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.