Base64 编码是计算机领域最基础的数据编码方案之一。每天有数百万开发者使用 base64 encode 和 base64 decode 操作来嵌入图片到 HTML、通过文本协议传输二进制数据以及处理认证令牌。无论你需要一个快速的 base64 编码器来处理一次性任务,还是想深入理解算法,本综合指南涵盖了从底层 6 位映射到 JavaScript、Python、Bash 和 PowerShell 实际代码示例的所有内容。如果你想在线进行 base64 编码解码,我们的免费工具可以即时完成。
什么是 Base64 编码?
Base64 是一种二进制到文本的编码方案,使用 64 个可打印 ASCII 字符来表示二进制数据。"Base64"这个名称来自它使用的 64 字符字母表:A-Z(26个)、a-z(26个)、0-9(10个)以及两个额外符号 + 和 /。第 65 个字符 = 用于填充。Base64 编码器以 3 字节(24 位)为一组处理输入数据,将其转换为 4 个 Base64 字符(4 x 6 位 = 24 位)。
该算法将每三个字节的输入拆分为四个 6 位组。每个 6 位值(范围 0 到 63)映射到 Base64 字母表中的一个字符。当输入长度不是三的倍数时,编码器添加 = 填充字符以确保输出长度始终是四的倍数。一个字节的余数产生两个 Base64 字符后跟 ==,两个字节的余数产生三个 Base64 字符后跟 =。
Base64 编码会使数据大小增加约 33%(4:3 的比率)。这种开销是为了能够通过纯文本通道(如电子邮件、JSON、XML 和 URL 查询参数)安全传输二进制数据而付出的代价。尽管体积增加,Base64 编码仍是标准选择,因为它简单、普遍支持,且不需要转义特殊字符。
Base64 编码/解码工作原理
让我们逐步演示 base64 编码过程,将 ASCII 字符串 Man 转换为 Base64:
- 转换为 ASCII 字节:
M= 77 (01001101),a= 97 (01100001),n= 110 (01101110)。 - 连接位串:01001101 01100001 01101110(共 24 位)。
- 分成 6 位组:010011 | 010110 | 000101 | 101110。
- 将每个 6 位值转为十进制:19、22、5、46。
- 查表映射为 Base64 字符:19 =
T,22 =W,5 =F,46 =u。
结果是 TWFu。要 base64 解码此字符串,逆转过程:查表获取每个字符的 6 位值,连接所有位,再拆分为 8 位字节恢复原始数据。
填充示例:编码 Ma(仅 2 字节 = 16 位)产生位串 01001101 01100001。需要 18 位(三个 6 位组)对应三个 Base64 字符,因此追加两个零位:010011 | 010110 | 000100。映射为 TWE 加一个 = 填充,最终结果为 TWE=。对于单字节 M,结果是 TQ==,带两个填充字符。
常见 Base64 使用场景
Base64 编码在现代软件开发中无处不在。以下是最重要的使用场景:
数据 URI(Base64 编码图片):你可以使用数据 URI 将图片直接嵌入 HTML 或 CSS,如 data:image/png;base64,iVBOR...。这消除了小图片(如图标、Logo 和缩略图)的额外 HTTP 请求。Base64 编码图片广泛用于电子邮件签名、单页应用和 CSS 精灵图。
电子邮件附件(MIME):MIME 标准使用 Base64 编码电子邮件中的二进制附件。由于电子邮件协议(SMTP)最初设计为传输 7 位 ASCII 文本,图片、PDF 等二进制文件必须先进行 Base64 编码才能作为附件。
API 认证(HTTP Basic Auth):HTTP 基本认证使用 Base64 编码 username:password 对,放入 Authorization: Basic 请求头。虽然 Base64 不是加密,但它确保凭据作为 ASCII 文本安全传输。始终使用 HTTPS 保护 Base64 编码的凭据。
JSON Web Token(JWT):JWT 由三段 Base64URL 编码的部分组成:header.payload.signature。开发者经常需要 base64 解码 JWT 段进行调试和检查。
URL 安全数据传输:当需要通过 URL、Cookie 或查询参数传递二进制或结构化数据时,Base64 编码确保数据仅包含安全的 ASCII 字符。Base64URL 变体使用 - 和 _ 替代 + 和 /,专为 URL 上下文设计。
Base64 编码/解码代码示例
JavaScript Base64 编码/解码
在浏览器中,JavaScript base64 编码使用 btoa(),解码使用 atob()。Node.js 中使用 Buffer 类。注意 btoa() 只处理 Latin-1 字符;对于 Unicode 字符串,需要先编码为 UTF-8:
// ===== Browser: btoa() and atob() =====
// Base64 encode a string
const encoded = btoa('Hello World');
console.log(encoded); // "SGVsbG8gV29ybGQ="
// Base64 decode a string
const decoded = atob('SGVsbG8gV29ybGQ=');
console.log(decoded); // "Hello World"
// Handle Unicode strings (btoa only supports Latin-1)
function base64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(
/%([0-9A-F]{2})/g,
(_, p1) => String.fromCharCode(parseInt(p1, 16))
));
}
function base64DecodeUnicode(str) {
return decodeURIComponent(
Array.from(atob(str))
.map(c => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))
.join('')
);
}
base64EncodeUnicode('Hello 🌍'); // "SGVsbG8g8J+MjQ=="
base64DecodeUnicode('SGVsbG8g8J+MjQ=='); // "Hello 🌍"
// ===== Node.js: Buffer =====
// Encode
const buf = Buffer.from('Hello World', 'utf-8');
const b64 = buf.toString('base64');
console.log(b64); // "SGVsbG8gV29ybGQ="
// Decode
const original = Buffer.from(b64, 'base64').toString('utf-8');
console.log(original); // "Hello World"
// URL-safe Base64 in Node.js
const urlSafe = buf.toString('base64url');
console.log(urlSafe); // "SGVsbG8gV29ybGQ"Python Base64 编码/解码
Python 中 base64 编码使用内置的 base64 模块。该模块提供标准 Base64、URL 安全 Base64 等多种变体的函数:
import base64
# Standard Base64 encode
text = "Hello World"
encoded = base64.b64encode(text.encode('utf-8'))
print(encoded) # b'SGVsbG8gV29ybGQ='
print(encoded.decode()) # "SGVsbG8gV29ybGQ="
# Standard Base64 decode
decoded = base64.b64decode(encoded)
print(decoded.decode('utf-8')) # "Hello World"
# URL-safe Base64 (replaces + with - and / with _)
url_encoded = base64.urlsafe_b64encode(text.encode('utf-8'))
print(url_encoded.decode()) # "SGVsbG8gV29ybGQ="
url_decoded = base64.urlsafe_b64decode(url_encoded)
print(url_decoded.decode('utf-8')) # "Hello World"
# Encode a file (e.g., an image)
with open('image.png', 'rb') as f:
image_b64 = base64.b64encode(f.read()).decode('utf-8')
data_uri = f"data:image/png;base64,{image_b64}"
# Decode Base64 back to file
with open('output.png', 'wb') as f:
f.write(base64.b64decode(image_b64))Bash / Linux Base64 编码/解码
在 Linux 和 macOS 上,bash base64 编码使用 base64 命令行工具。这是从终端进行 linux base64 编码的最简方式:
# Base64 encode a string (Linux)
echo -n "Hello World" | base64
# Output: SGVsbG8gV29ybGQ=
# Base64 decode a string (Linux)
echo "SGVsbG8gV29ybGQ=" | base64 --decode
# Output: Hello World
# macOS uses -D instead of --decode
echo "SGVsbG8gV29ybGQ=" | base64 -D
# Output: Hello World
# Base64 encode a file
base64 image.png > image_b64.txt
# Base64 decode a file
base64 --decode image_b64.txt > restored_image.png
# Encode and use inline (e.g., for curl auth header)
AUTH=$(echo -n "user:password" | base64)
curl -H "Authorization: Basic $AUTH" https://api.example.com/data
# Pipe from/to files
cat document.pdf | base64 > document_b64.txt
cat document_b64.txt | base64 --decode > restored.pdf
# Wrap lines at 76 characters (MIME standard)
echo -n "Long text..." | base64 -w 76PowerShell Base64 编码/解码
在 Windows PowerShell 中,base64 编码使用 .NET 的 [Convert] 类。PowerShell 默认使用 UTF-16LE 编码:
# PowerShell Base64 encode (UTF-16LE by default)
$text = "Hello World"
$bytes = [System.Text.Encoding]::UTF8.GetBytes($text)
$encoded = [Convert]::ToBase64String($bytes)
Write-Output $encoded
# Output: SGVsbG8gV29ybGQ=
# PowerShell Base64 decode
$decoded = [Convert]::FromBase64String($encoded)
$original = [System.Text.Encoding]::UTF8.GetString($decoded)
Write-Output $original
# Output: Hello World
# Encode a file to Base64
$fileBytes = [IO.File]::ReadAllBytes("C:\image.png")
$fileBase64 = [Convert]::ToBase64String($fileBytes)
# Decode Base64 to file
$decodedBytes = [Convert]::FromBase64String($fileBase64)
[IO.File]::WriteAllBytes("C:\restored.png", $decodedBytes)
# One-liner for encoding strings (UTF-8)
[Convert]::ToBase64String(
[Text.Encoding]::UTF8.GetBytes("Hello World")
)
# Using UTF-16LE (default Windows encoding)
$utf16 = [Convert]::ToBase64String(
[Text.Encoding]::Unicode.GetBytes("Hello World")
)
# Note: UTF-16LE produces different output than UTF-8Base64 编码表
完整的 Base64 字母表将每个 6 位值(0-63)映射到一个可打印 ASCII 字符。这是 RFC 4648 定义的标准表:
| Value | Char | Value | Char | Value | Char | Value | Char |
|---|---|---|---|---|---|---|---|
| 0 | A | 16 | Q | 32 | g | 48 | w |
| 1 | B | 17 | R | 33 | h | 49 | x |
| 2 | C | 18 | S | 34 | i | 50 | y |
| 3 | D | 19 | T | 35 | j | 51 | z |
| 4 | E | 20 | U | 36 | k | 52 | 0 |
| 5 | F | 21 | V | 37 | l | 53 | 1 |
| 6 | G | 22 | W | 38 | m | 54 | 2 |
| 7 | H | 23 | X | 39 | n | 55 | 3 |
| 8 | I | 24 | Y | 40 | o | 56 | 4 |
| 9 | J | 25 | Z | 41 | p | 57 | 5 |
| 10 | K | 26 | a | 42 | q | 58 | 6 |
| 11 | L | 27 | b | 43 | r | 59 | 7 |
| 12 | M | 28 | c | 44 | s | 60 | 8 |
| 13 | N | 29 | d | 45 | t | 61 | 9 |
| 14 | O | 30 | e | 46 | u | 62 | + |
| 15 | P | 31 | f | 47 | v | 63 | / |
Padding: =
Base64 URL 安全编码
标准 Base64 使用 + 和 / 字符,这些在 URL 中有特殊含义。Base64URL 编码用 URL 安全的替代字符:+ 变为 -(连字符),/ 变为 _(下划线)。此外,= 填充通常被省略,因为数据长度可以推断。
Base64URL 定义在 RFC 4648 第 5 节,是 JWT、OAuth 2.0 PKCE 代码验证器和许多现代 API 使用的编码。当你为 URL、查询参数或文件名进行 base64 编码时,始终使用 URL 安全变体以避免编码问题。
以下是标准 Base64 与 Base64URL 编码的对比:
// Standard Base64 vs Base64URL comparison
// Standard Base64 (RFC 4648 Section 4)
// Alphabet: A-Z, a-z, 0-9, +, /
// Padding: = (required)
"Hello World?" → "SGVsbG8gV29ybGQ/" // contains /
"subjects?" → "c3ViamVjdHM/" // contains /
"<<???>>" → "PDw/Pz8+Pg==" // contains + and =
// Base64URL (RFC 4648 Section 5)
// Alphabet: A-Z, a-z, 0-9, -, _
// Padding: omitted (optional)
"Hello World?" → "SGVsbG8gV29ybGQ_" // / replaced with _
"subjects?" → "c3ViamVjdHM_" // / replaced with _
"<<???>>" → "PDw_Pz8-Pg" // + → -, / → _, no padding
// JavaScript conversion between formats
function base64ToBase64Url(base64) {
return base64
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
}
function base64UrlToBase64(base64url) {
let base64 = base64url
.replace(/-/g, '+')
.replace(/_/g, '/');
// Add padding
while (base64.length % 4 !== 0) {
base64 += '=';
}
return base64;
}Base64 图片编码
Base64 最流行的用途之一是将图片直接嵌入 HTML 和 CSS。当你 base64 编码图片文件时,会创建一个数据 URI 来替代图片 URL。格式为:data:[媒体类型];base64,[编码数据]。
Base64 编码图片的常见场景包括:HTML 邮件中的内联图片(外部 URL 可能被阻止)、直接嵌入 CSS 的小图标和 UI 元素(消除 HTTP 请求)、JSON API 响应中嵌入图片、以及单页应用中打包资源。
性能考虑:Base64 编码的图片比原始二进制文件大约大 33%。对于大于几 KB 的图片,通常以独立文件加适当缓存头的方式提供更高效。Base64 嵌入最适合小图片(10KB 以下)、内联 SVG 和需要减少 HTTP 请求的场景。
在 HTML 中使用 Base64 图片:
<!-- Inline Base64 image in HTML -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAADElEQVQI12P4//8/AwAI/AL+hc2rNAAAAABJRU5E
rkJggg==" alt="Red dot" width="5" height="5" />
<!-- Base64 SVG in HTML -->
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDov
L3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMT
AwIj48Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI0MCIgZmlsbD0icmVk
Ii8+PC9zdmc+" alt="Red circle" />
<!-- Base64 favicon -->
<link rel="icon" href="data:image/x-icon;base64,AAABAA..." />在 CSS 中使用 Base64 图片:
/* Base64 background image in CSS */
.icon-check {
background-image: url('data:image/svg+xml;base64,PHN2ZyB4bW...');
background-size: contain;
width: 24px;
height: 24px;
}
/* Base64 cursor in CSS */
.custom-cursor {
cursor: url('data:image/png;base64,iVBORw0KGgo...'), auto;
}
/* Base64 font in CSS (@font-face) */
@font-face {
font-family: 'CustomFont';
src: url('data:font/woff2;base64,d09GMgABAAAAAD...') format('woff2');
}在 JavaScript(浏览器)中将图片转换为 Base64:
// Convert image file to Base64 data URI (browser)
function imageToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
// Usage with file input
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async (e) => {
const file = e.target.files[0];
const dataUri = await imageToBase64(file);
console.log(dataUri);
// "data:image/png;base64,iVBORw0KGgo..."
});
// Convert canvas to Base64
const canvas = document.getElementById('myCanvas');
const base64Image = canvas.toDataURL('image/png');
// "data:image/png;base64,iVBORw0KGgo..."
// Node.js: encode image file to Base64
const fs = require('fs');
const imageBuffer = fs.readFileSync('photo.jpg');
const base64String = imageBuffer.toString('base64');
const dataUri = `data:image/jpeg;base64,${base64String}`;常见问题
Base64 编码用于什么?
Base64 编码用于将二进制数据转换为 ASCII 文本,以便通过文本协议安全传输。最常见的场景包括:通过数据 URI 在 HTML/CSS 中嵌入图片、编码电子邮件附件(MIME)、在 JSON/XML API 中传输二进制数据、HTTP 基本认证头、JWT 以及在纯文本数据库或配置文件中存储二进制数据。
如何在 JavaScript 中 Base64 编码字符串?
在浏览器中,使用 btoa() 进行 Base64 编码:btoa("Hello World") 返回 "SGVsbG8gV29ybGQ="。解码使用 atob("SGVsbG8gV29ybGQ=") 返回 "Hello World"。对于 Unicode 字符串,先编码为 UTF-8:btoa(unescape(encodeURIComponent(text)))。在 Node.js 中,使用 Buffer.from("Hello World").toString("base64") 编码。
Base64 编码和加密一样吗?
不,Base64 编码不是加密。Base64 是一种可逆编码方案,任何人无需密钥即可解码。它不提供安全性,不应用于保护敏感数据。Base64 只是将二进制数据转换为文本格式以便安全传输。如果需要保护数据,请使用 AES-256 或 RSA 等加密算法。
Base64 编码是每个开发者的基础技能。从在数据 URI 中嵌入图片到调试 JWT 令牌,理解如何 base64 编码和解码数据对于现代 Web 开发至关重要。收藏本指南以备参考,并使用我们的免费在线工具进行即时编码和解码。