Base64 编解码是开发者在处理 API、证书、Kubernetes secrets 和数据管道时的日常任务。与其每次都打开在线工具,不如掌握 Linux、macOS 和 Windows 上的原生命令,直接在终端中完成 Base64 编解码。
为什么要在命令行中使用 Base64?
在线 Base64 工具虽然方便,但有一个隐患:你可能将敏感数据(API 密钥、证书、密码)发送到第三方服务器。命令行操作完全在本地进行,可脚本化,且无需网络连接。
命令行 Base64 的常见使用场景:
- 从字面值创建 Kubernetes secrets
- 为 HTTP Basic 认证编码 API 凭证
- 将小图片编码为 CSS/HTML 中的 data URI
- 编解码 JWT 令牌载荷用于调试
- 在 shell 脚本和 CI/CD 管道中处理二进制数据
Linux(GNU base64)
大多数 Linux 发行版都包含 GNU coreutils 中的 base64 命令。它从标准输入或文件读取,将结果写入标准输出。
编码字符串
# Encode a string (note: echo -n avoids trailing newline)
echo -n "Hello, World!" | base64
# Output: SGVsbG8sIFdvcmxkIQ==
# WRONG: echo without -n includes a newline
echo "Hello, World!" | base64
# Output: SGVsbG8sIFdvcmxkIQo= (different! encodes "Hello, World!\n")
# Encode using printf (safer, more portable)
printf "Hello, World!" | base64
# Output: SGVsbG8sIFdvcmxkIQ==
# Encode a multi-line string
printf "line1\nline2\nline3" | base64
# Output: bGluZTEKbGluZTIKbGluZTM=解码字符串
# Decode a Base64 string
echo "SGVsbG8sIFdvcmxkIQ==" | base64 -d
# Output: Hello, World!
# Decode using printf
printf "SGVsbG8sIFdvcmxkIQ==" | base64 -d
# Output: Hello, World!
# Decode and show hex output (useful for binary data)
echo "SGVsbG8=" | base64 -d | xxd编解码文件
# Encode a file
base64 input.txt > encoded.txt
# Encode a file without line wrapping
base64 -w 0 input.txt > encoded.txt
# Decode a file
base64 -d encoded.txt > decoded.txt
# Encode a binary file (image, PDF, etc.)
base64 -w 0 image.png > image_base64.txt
# Decode back to binary
base64 -d image_base64.txt > restored_image.png管道用法
命令行 Base64 的真正强大之处在于管道。你可以将它与任何产生输出的命令串联。
# Encode the output of any command
cat /etc/hostname | base64
# Encode a curl response
curl -s https://api.example.com/data | base64 -w 0
# Decode and pipe to jq for JSON processing
echo "eyJuYW1lIjoiSm9obiJ9" | base64 -d | jq .
# Generate a random Base64 token
head -c 32 /dev/urandom | base64 -w 0
# Encode environment variable content
echo -n "$API_KEY" | base64 -w 0换行控制
默认情况下,GNU base64 在第 76 个字符处换行。使用 -w 0 禁用换行(这对 URL、JSON、环境变量很重要)。
# Default: wraps at 76 characters
echo -n "This is a long string that will demonstrate line wrapping behavior in base64 encoding output" | base64
# VGhpcyBpcyBhIGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBkZW1vbnN0cmF0ZSBsaW5lIHdy
# YXBwaW5nIGJlaGF2aW9yIGluIGJhc2U2NCBlbmNvZGluZyBvdXRwdXQ=
# No wrapping: single line output
echo -n "This is a long string that will demonstrate line wrapping behavior in base64 encoding output" | base64 -w 0
# VGhpcyBpcyBhIGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBkZW1vbnN0cmF0ZSBsaW5lIHdyYXBwaW5nIGJlaGF2aW9yIGluIGJhc2U2NCBlbmNvZGluZyBvdXRwdXQ=macOS(BSD base64)
macOS 使用 BSD 版本的 base64,其标志与 GNU 版本略有不同。最显著的区别是解码标志。
编码字符串
# Encode a string
echo -n "Hello, World!" | base64
# Output: SGVsbG8sIFdvcmxkIQ==
# Encode using printf
printf "Hello, World!" | base64
# Output: SGVsbG8sIFdvcmxkIQ==解码字符串
关键区别:macOS 使用大写 -D 解码,而 Linux 使用小写 -d。某些较新的 macOS 版本也接受 -d,但 -D 是安全、可移植的选择。
# Decode with -D (uppercase) — macOS standard
echo "SGVsbG8sIFdvcmxkIQ==" | base64 -D
# Output: Hello, World!
# Some newer macOS versions also accept lowercase -d
echo "SGVsbG8sIFdvcmxkIQ==" | base64 -d
# Output: Hello, World!
# Decode from a file
base64 -D -i encoded.txt
# or
base64 -D < encoded.txt编解码文件
# Encode a file
base64 -i input.txt -o encoded.txt
# Decode a file
base64 -D -i encoded.txt -o decoded.txt
# Encode a binary file
base64 -i image.png -o image_base64.txt
# Decode back to binary
base64 -D -i image_base64.txt -o restored_image.png换行控制
macOS base64 默认不换行。要显式设置行长度,使用 -b(break):
# macOS: no wrapping by default (unlike Linux)
# Force wrapping at 76 characters
echo -n "long string here" | base64 -b 76
# Force wrapping at 64 characters (MIME standard)
echo -n "long string here" | base64 -b 64Windows PowerShell
Windows 没有内置的 base64 命令,但 PowerShell 提供了 .NET 方法,certutil 也可作为系统工具使用。
PowerShell:编码
# Encode a string in PowerShell
[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("Hello, World!"))
# Output: SGVsbG8sIFdvcmxkIQ==
# Store in a variable
$encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("Hello, World!"))
Write-Output $encoded
# Encode from a variable
$mySecret = "api-key-12345"
[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($mySecret))
# Encode file contents
$bytes = [IO.File]::ReadAllBytes("C:\path\to\file.txt")
[Convert]::ToBase64String($bytes)
# Encode file and save to another file
$bytes = [IO.File]::ReadAllBytes("C:\path\to\input.txt")
$encoded = [Convert]::ToBase64String($bytes)
Set-Content -Path "C:\path\to\encoded.txt" -Value $encodedPowerShell:解码
# Decode a Base64 string in PowerShell
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("SGVsbG8sIFdvcmxkIQ=="))
# Output: Hello, World!
# Decode and save to file
$decoded = [Convert]::FromBase64String("SGVsbG8sIFdvcmxkIQ==")
[IO.File]::WriteAllBytes("C:\path\to\decoded.txt", $decoded)
# Decode from file content
$encoded = Get-Content -Path "C:\path\to\encoded.txt" -Raw
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded.Trim()))certutil(传统方法)
certutil 是 Windows 内置工具,最初用于证书管理,但也可以编解码 Base64 文件。注意:它只能处理文件,不能直接处理内联字符串。
# Encode a file with certutil
certutil -encode input.txt encoded.txt
# Decode a file with certutil
certutil -decode encoded.txt decoded.txt
# Note: certutil adds "-----BEGIN CERTIFICATE-----" headers
# To get clean Base64, strip the first and last lines:
certutil -encode input.txt temp.txt
findstr /v CERTIFICATE temp.txt > clean_encoded.txt
del temp.txtOpenSSL(跨平台)
OpenSSL 安装在大多数系统上(Linux、macOS、Windows 可通过 Git Bash 或 WSL 使用),提供跨平台一致的 Base64 接口。
使用 OpenSSL 编码
# Encode a string
echo -n "Hello, World!" | openssl base64
# Output: SGVsbG8sIFdvcmxkIQ==
# Encode without line wrapping (single line)
echo -n "Hello, World!" | openssl base64 -A
# Output: SGVsbG8sIFdvcmxkIQ==
# Shorter alias: openssl enc -base64
echo -n "Hello, World!" | openssl enc -base64
# Output: SGVsbG8sIFdvcmxkIQ==使用 OpenSSL 解码
# Decode a string
echo "SGVsbG8sIFdvcmxkIQ==" | openssl base64 -d
# Output: Hello, World!
# Decode a single-line Base64 (no newlines)
echo -n "SGVsbG8sIFdvcmxkIQ==" | openssl base64 -d -A
# Output: Hello, World!
# Shorter alias
echo "SGVsbG8sIFdvcmxkIQ==" | openssl enc -base64 -d
# Output: Hello, World!文件操作
# Encode a file
openssl base64 -in input.txt -out encoded.txt
# Encode without line wrapping
openssl base64 -A -in input.txt -out encoded.txt
# Decode a file
openssl base64 -d -in encoded.txt -out decoded.txt
# Encode a binary file (image, certificate, etc.)
openssl base64 -in image.png -out image_base64.txt
# Decode back to binary
openssl base64 -d -in image_base64.txt -out restored_image.pngBash 一行命令
常见 Base64 任务的即用一行命令。这些命令适用于 Linux 和 macOS(macOS 上需要调整解码标志)。
将文件编码为 Base64 字符串
# Linux: encode file to single-line Base64
base64 -w 0 myfile.txt && echo
# macOS: encode file (already single-line)
base64 -i myfile.txt
# Cross-platform with OpenSSL
openssl base64 -A -in myfile.txt && echo将 Base64 字符串解码为文件
# Linux: decode Base64 string and save to file
echo "SGVsbG8sIFdvcmxkIQ==" | base64 -d > output.txt
# macOS
echo "SGVsbG8sIFdvcmxkIQ==" | base64 -D > output.txt
# Decode a Base64-encoded file
base64 -d encoded.txt > original.bin从管道编码
# Encode output of any command
date | base64
# Encode a JSON payload
echo -n '{"user":"admin","pass":"secret"}' | base64 -w 0
# Encode the contents of a web page
curl -s https://example.com | base64 -w 0 > page_encoded.txt
# Generate a random password and Base64 encode it
openssl rand 24 | base64 -w 0剪贴板集成
# macOS: encode clipboard contents
pbpaste | base64 | pbcopy
# macOS: decode clipboard contents
pbpaste | base64 -D | pbcopy
# Linux (with xclip): encode clipboard
xclip -selection clipboard -o | base64 -w 0 | xclip -selection clipboard
# Linux (with xclip): decode clipboard
xclip -selection clipboard -o | base64 -d | xclip -selection clipboard
# Linux (with xsel): encode clipboard
xsel --clipboard --output | base64 -w 0 | xsel --clipboard --inputKubernetes Secrets
# Create a Kubernetes secret value
echo -n "my-db-password" | base64 -w 0
# Output: bXktZGItcGFzc3dvcmQ=
# Decode a Kubernetes secret
kubectl get secret my-secret -o jsonpath="{.data.password}" | base64 -d
# Decode all secrets at once (requires jq)
kubectl get secret my-secret -o json | jq -r '.data | to_entries[] | "\(.key): \(.value | @base64d)"'
# Create a secret from a file
kubectl create secret generic my-secret --from-file=key.pem解码 JWT 载荷
# Decode JWT payload (second part between the dots)
JWT="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0IiwibmFtZSI6IkpvaG4ifQ.signature"
# Extract and decode the payload
echo "$JWT" | cut -d'.' -f2 | base64 -d 2>/dev/null | jq .
# Output: { "sub": "1234", "name": "John" }
# Handle Base64URL padding (JWT uses Base64URL)
PAYLOAD=$(echo "$JWT" | cut -d'.' -f2)
# Add padding if needed
MOD=$(($(echo -n "$PAYLOAD" | wc -c) % 4))
[ $MOD -eq 2 ] && PAYLOAD="$PAYLOAD=="
[ $MOD -eq 3 ] && PAYLOAD="$PAYLOAD="
echo "$PAYLOAD" | tr '_-' '/+' | base64 -d | jq .常见陷阱
以下是开发者在命令行中使用 Base64 时最常遇到的问题。
1. 输入末尾的换行符
echo 默认会在字符串末尾添加换行符,该换行符会被编码到 Base64 输出中。这是编码 API 密钥或密码时最常见的 Bug 来源。
# WRONG: includes trailing newline
echo "secret" | base64
# c2VjcmV0Cg== (encodes "secret\n")
# CORRECT: no trailing newline
echo -n "secret" | base64
# c2VjcmV0 (encodes "secret")
# SAFEST: use printf (works on all shells)
printf "secret" | base64
# c2VjcmV02. 填充字符(=)
Base64 输出使用 = 字符填充,使长度为 4 的倍数。某些系统(如 URL 或 JWT)使用去除填充的 Base64URL 编码。除非接收方期望 Base64URL,否则不要去除填充。
# Standard Base64 with padding
echo -n "a" | base64 # YQ== (2 padding chars)
echo -n "ab" | base64 # YWI= (1 padding char)
echo -n "abc"| base64 # YWJj (no padding needed)
# Do NOT strip padding unless the receiver expects Base64URL
# Many APIs will reject Base64 with missing padding3. 二进制模式与文本模式
在 Windows 上要注意换行符。Windows 使用 \r\n(CRLF),而 Linux/macOS 使用 \n(LF)。跨平台编码文件时,"相同"的文本文件可能产生不同的 Base64 输出。
# Check line endings of a file
file myfile.txt
# myfile.txt: ASCII text, with CRLF line terminators (Windows)
# myfile.txt: ASCII text (Unix/Mac)
# Convert Windows line endings to Unix before encoding
dos2unix myfile.txt && base64 -w 0 myfile.txt
# Or strip \r inline
cat myfile.txt | tr -d '\r' | base64 -w 04. 换行差异
GNU base64 默认在 76 字符处换行。macOS base64 不换行。OpenSSL 在 64 字符处换行。比较跨平台 Base64 输出时,先删除换行符进行规范化。
# Normalize Base64 output for comparison
# Remove all newlines from Base64 output
base64 file.txt | tr -d '\n'
# Compare Base64 from different platforms
diff <(base64 -w 0 file.txt) <(ssh mac-host 'base64 -i file.txt')5. Base64 与 Base64URL
标准 Base64 使用 + 和 /,这些字符在 URL 中不安全。Base64URL 用 - 和 _ 替换它们。大多数命令行工具只支持标准 Base64。转换为 Base64URL 可以使用 tr 或 sed:
# Convert standard Base64 to Base64URL
echo -n "Hello+World/Foo==" | tr '+/' '-_' | tr -d '='
# Output: Hello-World_Foo
# Convert Base64URL back to standard Base64
B64URL="SGVsbG8tV29ybGRfRm9v"
# Add padding
PADDED=$(echo -n "$B64URL" | awk '{while(length%4) $0=$0"="; print}')
# Replace URL-safe chars
echo "$PADDED" | tr '_-' '/+'
# Full pipeline: encode as Base64URL
echo -n "Hello, World!" | base64 -w 0 | tr '+/' '-_' | tr -d '='快速参考表
跨平台 Base64 命令对照表。收藏此表以备查阅。
| 任务 | Linux(GNU) | macOS(BSD) | Windows(PowerShell) | OpenSSL |
|---|---|---|---|---|
| Encode string | echo -n "str" | base64 | echo -n "str" | base64 | [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("str")) | echo -n "str" | openssl base64 |
| Decode string | echo "b64" | base64 -d | echo "b64" | base64 -D | [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("b64")) | echo "b64" | openssl base64 -d |
| Encode file | base64 file.txt | base64 -i file.txt | [Convert]::ToBase64String([IO.File]::ReadAllBytes("file")) | openssl base64 -in file.txt |
| Decode file | base64 -d enc.txt > out | base64 -D -i enc.txt -o out | certutil -decode enc.txt out | openssl base64 -d -in enc.txt -out out |
| No line wrap | base64 -w 0 | (default) | (default) | openssl base64 -A |
| Default wrap | 76 chars | No wrap | No wrap | 64 chars |
常见问题
为什么 echo "hello" | base64 的结果和预期不同?
echo 命令默认会在字符串末尾附加换行符(\n),所以实际编码的是 "hello\n" 而不是 "hello"。使用 echo -n "hello"(Linux)或 printf "hello"(跨平台)来避免尾部换行符。这是 Base64 命令行中最常见的错误。
如何将文件编码为不换行的 Base64?
在 Linux 上,使用 base64 -w 0 file.txt 禁用换行。macOS 上默认没有换行。使用 OpenSSL 时,通过管道 tr -d "\n" 去除换行:openssl base64 -in file.txt | tr -d "\n"。
base64 和 base64url 编码有什么区别?
标准 Base64 使用 + 和 / 字符,这些在 URL 中不安全。Base64URL 用 - 替换 +,用 _ 替换 /,通常省略填充(=)。JWT 令牌使用 Base64URL。大多数 CLI 工具只支持标准 Base64,需要使用 tr 或 sed 进行转换。
可以用 Base64 加密敏感数据吗?
不可以。Base64 是编码,不是加密。任何人都可以立即解码 Base64 数据,它提供零安全性。要保护敏感数据,请使用正确的加密工具,如 openssl enc -aes-256-cbc、gpg 或 age。Base64 仅用于将二进制数据转换为文本安全格式。
如何从命令行解码 Kubernetes secrets?
使用 kubectl get secret my-secret -o jsonpath="{.data.key}" | base64 -d(Linux)或 base64 -D(macOS)。也可以使用 kubectl get secret my-secret -o json | jq ".data | map_values(@base64d)" 一次解码所有值。
收藏此参考指南,方便下次使用 Base64 时查阅。如果不想打开终端,也可以使用我们的在线工具快速编解码。