DevToolBoxZA DARMO
Blog

Base64 kodowanie i dekodowanie z wiersza poleceń (Linux, Mac, Windows)

6 min czytaniaby DevToolBox

Base64 encoding and decoding is a daily task for developers working with APIs, certificates, Kubernetes secrets, and data pipelines. Instead of reaching for an online tool every time, learn the native commands available on Linux, macOS, and Windows so you can encode and decode Base64 directly from your terminal.

Try our online Base64 Encoder/Decoder tool →

Why Base64 from the Command Line?

Online Base64 tools are convenient but come with trade-offs: you are sending potentially sensitive data (API keys, certificates, secrets) to a third-party server. The command line keeps everything local, is scriptable, and works even without internet access.

Common use cases for command-line Base64:

  • Creating Kubernetes secrets from literal values
  • Encoding API credentials for HTTP Basic Authentication
  • Embedding small images as data URIs in CSS/HTML
  • Encoding/decoding JWT token payloads for debugging
  • Processing binary data in shell scripts and CI/CD pipelines

Linux (GNU base64)

Most Linux distributions include the base64 command from GNU coreutils. It reads from standard input or a file and writes the result to standard output.

Encode a String

# 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 String

# 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/Decode Files

# 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

Pipe Usage

The real power of command-line Base64 comes from piping. You can chain it with any command that produces output.

# 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

Line Wrapping

By default, GNU base64 wraps output at 76 characters. Use -w 0 to disable wrapping (important for URLs, JSON, environment variables).

# 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 uses the BSD version of base64, which has slightly different flags from the GNU version. The most notable difference is the decode flag.

Encode a String

# Encode a string
echo -n "Hello, World!" | base64
# Output: SGVsbG8sIFdvcmxkIQ==

# Encode using printf
printf "Hello, World!" | base64
# Output: SGVsbG8sIFdvcmxkIQ==

Decode a String

Key difference: macOS uses -D (uppercase) for decode, while Linux uses -d (lowercase). Some newer macOS versions also accept -d, but -D is the safe, portable choice.

# 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/Decode Files

# 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

Line Wrapping

macOS base64 does NOT wrap by default. To explicitly set line length, use -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 64

Windows PowerShell

Windows does not have a built-in base64 command, but PowerShell provides .NET methods and certutil is available as a system tool.

PowerShell: Encode

# 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 $encoded

PowerShell: Decode

# 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 (Legacy Method)

certutil is a built-in Windows tool originally for certificate management, but it can encode/decode Base64 files. Note: it works with files, not inline strings.

# 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.txt

OpenSSL (Cross-Platform)

OpenSSL is installed on most systems (Linux, macOS, Windows via Git Bash or WSL) and provides a consistent Base64 interface across platforms.

Encode with 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==

Decode with 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!

File Operations

# 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.png

Bash One-Liners

Copy-paste ready one-liners for common Base64 tasks. These work on Linux and macOS (adjust the decode flag for macOS if needed).

Encode a File to Base64 String

# 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

Decode Base64 String to File

# 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 from Pipe

# 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

Clipboard Integration

# 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 --input

Kubernetes 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

Decode JWT Payload

# 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 .

Common Pitfalls

These are the most frequent issues developers encounter when working with Base64 on the command line.

1. Trailing Newline in Input

echo appends a newline character by default, which gets encoded into the Base64 output. This is the #1 source of bugs when encoding strings for API keys or passwords.

# 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
# c2VjcmV0

2. Padding Characters (=)

Base64 output is padded with = characters to make the length a multiple of 4. Some systems (like URLs or JWT) use Base64URL encoding which removes padding. Do not strip padding unless the receiving system expects 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 padding

3. Binary vs Text Mode

On Windows, be careful with line endings. Windows uses \r\n (CRLF) while Linux/macOS uses \n (LF). When encoding files across platforms, this can produce different Base64 output for the "same" text file.

# 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 0

4. Line Wrapping Differences

GNU base64 wraps at 76 characters by default. macOS base64 does not wrap. OpenSSL wraps at 64 characters. When comparing Base64 output across platforms, always normalize by removing newlines first.

# 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 vs Base64URL

Standard Base64 uses + and / which are not URL-safe. Base64URL replaces them with - and _. Most command-line tools only support standard Base64. For Base64URL, use tr or 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 '='

Quick Reference Table

A side-by-side comparison of Base64 commands across all platforms. Bookmark this table.

TaskLinux (GNU)macOS (BSD)Windows (PowerShell)OpenSSL
Encode stringecho -n "str" | base64echo -n "str" | base64[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("str"))echo -n "str" | openssl base64
Decode stringecho "b64" | base64 -decho "b64" | base64 -D[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("b64"))echo "b64" | openssl base64 -d
Encode filebase64 file.txtbase64 -i file.txt[Convert]::ToBase64String([IO.File]::ReadAllBytes("file"))openssl base64 -in file.txt
Decode filebase64 -d enc.txt > outbase64 -D -i enc.txt -o outcertutil -decode enc.txt outopenssl base64 -d -in enc.txt -out out
No line wrapbase64 -w 0(default)(default)openssl base64 -A
Default wrap76 charsNo wrapNo wrap64 chars

Frequently Asked Questions

Why does echo "hello" | base64 give a different result than expected?

The echo command appends a trailing newline (\n) to the string, so you are actually encoding "hello\n" instead of "hello". Use echo -n "hello" (Linux) or printf "hello" (cross-platform) to avoid the trailing newline. This is the most common Base64 command-line mistake.

How do I Base64 encode a file without line breaks?

On Linux, use base64 -w 0 file.txt to disable line wrapping. On macOS, the output has no wrapping by default. With OpenSSL, pipe through tr -d "\n" to remove line breaks: openssl base64 -in file.txt | tr -d "\n".

What is the difference between base64 and base64url encoding?

Standard Base64 uses + and / characters, which are not safe in URLs. Base64URL replaces + with - and / with _, and typically omits padding (=). JWT tokens use Base64URL. Most CLI tools only support standard Base64, so you need to convert using tr or sed.

Can I use Base64 to encrypt sensitive data?

No. Base64 is an encoding, not encryption. Anyone can decode Base64 data instantly. It provides zero security. For protecting sensitive data, use proper encryption tools like openssl enc -aes-256-cbc, gpg, or age. Base64 is only for converting binary data to a text-safe format.

How do I decode Kubernetes secrets from the command line?

Use kubectl get secret my-secret -o jsonpath="{.data.key}" | base64 -d (Linux) or base64 -D (macOS). You can also decode all values at once using kubectl get secret my-secret -o json | jq ".data | map_values(@base64d)".

Bookmark this reference and keep it handy for your next Base64 task. For quick encoding and decoding without opening a terminal, try our online tool.

Try the Base64 Encoder/Decoder →

𝕏 Twitterin LinkedIn
Czy to było pomocne?

Bądź na bieżąco

Otrzymuj cotygodniowe porady i nowe narzędzia.

Bez spamu. Zrezygnuj kiedy chcesz.

Try These Related Tools

B64Base64 Encoder/Decoder01Text ↔ Binary ConverterB→Base64 Encoder→BBase64 Decoder

Related Articles

Base64 w Praktyce: 7 Zastosowań, Które Każdy Programista Powinien Znać

Odkryj 7 praktycznych zastosowań Base64: obrazy w HTML, sekrety Kubernetes, tokeny JWT i data URIs.

Osadzanie obrazów Base64 w HTML, CSS i email: Kompletny przewodnik

Osadzaj obrazy jako Base64 data URI w HTML, CSS i email.