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

推荐订阅源

J
Java Code Geeks
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
博客园 - Franky
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
腾讯CDC
D
Docker
The Cloudflare Blog
量子位
爱范儿
爱范儿
L
LangChain Blog
博客园 - 三生石上(FineUI控件)
博客园 - 司徒正美
aimingoo的专栏
aimingoo的专栏
Blog — PlanetScale
Blog — PlanetScale
Jina AI
Jina AI
Apple Machine Learning Research
Apple Machine Learning Research
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
Vercel News
Vercel News
MyScale Blog
MyScale Blog

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 en JavaScript: codificación, decodificación y caso...
ToolRapido · 2026-05-02 · via DEV Community

ToolRapido

Base64 aparece en todas partes del desarrollo web: imágenes incrustadas en CSS, tokens JWT, APIs REST, cabeceras de autenticación. Aquí tienes todo lo que necesitas saber.

Las funciones nativas: btoa() y atob()

// Codificar
btoa('Hola mundo');         // 'SG9sYSBtdW5kbw=='
btoa('toolrapido.com');     // 'dG9vbHJhcGlkby5jb20='

// Decodificar
atob('SG9sYSBtdW5kbw==');  // 'Hola mundo'

Enter fullscreen mode Exit fullscreen mode

El problema: btoa() solo acepta caracteres ASCII. Con caracteres Unicode (tildes, ñ, emojis) lanza un error.

El problema con Unicode

btoa('Ñoño');  // ❌ InvalidCharacterError

Enter fullscreen mode Exit fullscreen mode

La solución correcta en 2024 usa TextEncoder:

function toBase64(str) {
  const bytes = new TextEncoder().encode(str);
  const binary = Array.from(bytes, (b) => String.fromCharCode(b)).join('');
  return btoa(binary);
}

function fromBase64(str) {
  const binary = atob(str);
  const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

toBase64('Ñoño');           // 'w5Bvw5Bv' — funciona
fromBase64('w5Bvw5Bv');    // 'Ñoño'

Enter fullscreen mode Exit fullscreen mode

Base64 URL-safe

El Base64 estándar usa +, / y = que necesitan escaparse en URLs. La variante URL-safe los reemplaza:

function toBase64URL(str) {
  return toBase64(str)
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
}

function fromBase64URL(str) {
  const padded = str + '='.repeat((4 - str.length % 4) % 4);
  return fromBase64(padded.replace(/-/g, '+').replace(/_/g, '/'));
}

Enter fullscreen mode Exit fullscreen mode

Esta variante es la que usan los tokens JWT.

Data URLs: incrustar archivos en HTML/CSS

async function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result); // "data:image/png;base64,..."
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// Usar en una imagen
const img = document.createElement('img');
img.src = await fileToBase64(file);

Enter fullscreen mode Exit fullscreen mode

Decodificar un JWT manualmente

function decodeJWT(token) {
  const [header, payload] = token.split('.');
  return {
    header: JSON.parse(fromBase64URL(header)),
    payload: JSON.parse(fromBase64URL(payload)),
  };
}

const token = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMifQ.xxx';
decodeJWT(token).payload; // { sub: '123' }

Enter fullscreen mode Exit fullscreen mode

Ojo: esto solo decodifica, no verifica la firma. Nunca confíes en el payload sin verificar el JWT en el servidor.

Cuándo NO usar Base64

Base64 aumenta el tamaño un 33%. No uses Base64 para:

  • Transferir archivos grandes (usa multipart/form-data)
  • Almacenar contraseñas (usa bcrypt/argon2)
  • Cifrar datos (Base64 no es cifrado, solo codificación)

Herramienta online

Si necesitas codificar o decodificar Base64 rápidamente sin escribir código, puedes usar este codificador Base64 gratuito que funciona en el navegador.

Resumen

Caso Solución
ASCII simple btoa() / atob()
Unicode (tildes, ñ) TextEncoder + btoa()
URLs y JWT Base64 URL-safe
Imágenes en HTML Data URL con FileReader