Base64 Encode and Decode: Examples for Every Language
You need to Base64 encode or decode something, right now, in the language you are using. This page is a copy-paste reference: the command line (macOS, Linux, Windows), JavaScript, Node.js, Python, Java, C#, PHP and Go. Every example uses the same text, so you can check that your output matches. If you want to understand how Base64 works, read Base64 explained.
The test values
| Text | Base64 |
|---|---|
hello | aGVsbG8= |
héllo 👋 (with an accent and an emoji) | aMOpbGxvIPCfkYs= |
The second value is the real test: it only comes out right if your code uses UTF-8. Many "Base64 is broken" bugs are really encoding bugs.
Command line
macOS and Linux
# Encode
printf 'hello' | base64 # aGVsbG8=
# Decode
echo 'aGVsbG8=' | base64 --decode # hello
# Encode a file (Linux: add -w 0 to avoid line breaks every 76 characters)
base64 -i photo.png -o photo.txt # macOS
base64 -w 0 photo.png > photo.txt # Linux
# Decode a file
base64 --decode -i photo.txt -o photo.png # macOS
base64 --decode photo.txt > photo.png # Linuxecho 'hello' | base64 gives aGVsbG8K, not aGVsbG8=, because echo adds a line break at the end and that gets encoded too. Use printf or echo -n. This is the #1 reason a Base64 password or API key "doesn't work".Windows (PowerShell)
# Encode
[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("hello"))
# aGVsbG8=
# Decode
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("aGVsbG8="))
# hello
# Encode a file
[Convert]::ToBase64String([IO.File]::ReadAllBytes("C:\photo.png")) > photo.txtUse UTF8, not Unicode: in .NET, Unicode means UTF-16 and gives a completely different (and twice as long) result.
JavaScript in the browser
btoa() encodes and atob() decodes, but only for plain English letters:
btoa('hello') // 'aGVsbG8='
atob('aGVsbG8=') // 'hello'
btoa('héllo 👋') // ❌ InvalidCharacterError: characters outside of the Latin1 rangeFor any real text, convert to UTF-8 bytes first:
function toBase64(text) {
const bytes = new TextEncoder().encode(text)
let binary = ''
for (const b of bytes) binary += String.fromCharCode(b)
return btoa(binary)
}
function fromBase64(base64) {
const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))
return new TextDecoder().decode(bytes)
}
toBase64('héllo 👋') // 'aMOpbGxvIPCfkYs='
fromBase64('aMOpbGxvIPCfkYs=') // 'héllo 👋'bytes.toBase64() and Uint8Array.fromBase64(), which do the same without the loop. Use the functions above if you also support older browsers or Node.js.Node.js
// Encode (Buffer uses UTF-8 by default)
Buffer.from('héllo 👋').toString('base64') // 'aMOpbGxvIPCfkYs='
// Decode
Buffer.from('aMOpbGxvIPCfkYs=', 'base64').toString('utf8') // 'héllo 👋'
// Base64URL (for JWTs and URLs: no + / =)
Buffer.from('héllo 👋').toString('base64url') // 'aMOpbGxvIPCfkYs'
// A file
import { readFileSync } from 'node:fs'
const encoded = readFileSync('photo.png').toString('base64')Python
import base64
# Encode: text → bytes → Base64 bytes → text
base64.b64encode("héllo 👋".encode("utf-8")).decode("ascii")
# 'aMOpbGxvIPCfkYs='
# Decode
base64.b64decode("aMOpbGxvIPCfkYs=").decode("utf-8")
# 'héllo 👋'
# Base64URL
base64.urlsafe_b64encode(b"\xfb\xff").decode() # '-_8=' (standard: '+/8=')
# A file
with open("photo.png", "rb") as f:
encoded = base64.b64encode(f.read()).decode("ascii")b64encode takes and returns bytes, not text. That's why you need .encode() before and .decode() after. Passing a string gives TypeError: a bytes-like object is required, not 'str'.
Java
import java.util.Base64;
import java.nio.charset.StandardCharsets;
String encoded = Base64.getEncoder()
.encodeToString("héllo 👋".getBytes(StandardCharsets.UTF_8));
// aMOpbGxvIPCfkYs=
String decoded = new String(
Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
// héllo 👋
// Base64URL without padding
Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
// Base64 with line breaks (email, PEM): Base64.getMimeEncoder()Always pass StandardCharsets.UTF_8. Without it, Java uses the system default, and the same code can give different results on different servers.
C# / .NET
using System.Text;
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes("héllo 👋"));
// aMOpbGxvIPCfkYs=
string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
// héllo 👋
// A file
string fileBase64 = Convert.ToBase64String(File.ReadAllBytes("photo.png"));PHP
$encoded = base64_encode("héllo 👋"); // aMOpbGxvIPCfkYs= (PHP strings are bytes; UTF-8 source files work)
$decoded = base64_decode($encoded); // héllo 👋
// Strict mode: return false on invalid input instead of guessing
$decoded = base64_decode($input, true);Go
import "encoding/base64"
s := base64.StdEncoding.EncodeToString([]byte("héllo 👋"))
// aMOpbGxvIPCfkYs=
b, err := base64.StdEncoding.DecodeString(s)
// string(b) == "héllo 👋"
// Base64URL without padding (JWTs)
base64.RawURLEncoding.EncodeToString(data)Quick reference
| Language | Encode | Decode |
|---|---|---|
| Shell | printf 'x' | base64 | base64 --decode |
| PowerShell | [Convert]::ToBase64String(...) | [Convert]::FromBase64String(...) |
| Browser JS | btoa() + TextEncoder | atob() + TextDecoder |
| Node.js | Buffer.from(s).toString('base64') | Buffer.from(b, 'base64').toString() |
| Python | base64.b64encode(s.encode()) | base64.b64decode(b).decode() |
| Java | Base64.getEncoder().encodeToString() | Base64.getDecoder().decode() |
| C# | Convert.ToBase64String() | Convert.FromBase64String() |
| PHP | base64_encode() | base64_decode() |
| Go | base64.StdEncoding.EncodeToString() | base64.StdEncoding.DecodeString() |
When the result looks wrong
- Ends in
KorCg==when you didn't expect it: a line break was encoded. Useprintforecho -n, or.trim()the input. - Accented letters come out as
é: the text was decoded with the wrong character set. Decode the bytes as UTF-8. - "Invalid character" or "Incorrect padding": the input is probably Base64URL (it has
-or_, or no=at the end), common in JWTs. Use the URL-safe decoder, or the Base64 tool, which decodes both kinds. - The output is 33% bigger than the input: that is normal. Base64 turns every 3 bytes into 4 characters.