L'encodage Base64 est l'un des schemas d'encodage les plus utilises. Ce guide explique son fonctionnement, ses cas d'utilisation et fournit des exemples en JavaScript, Python et en ligne de commande.
Encodez et decodez Base64 avec notre outil gratuit.
Qu'est-ce que l'encodage Base64 ?
Base64 est un schema d'encodage binaire-vers-texte utilisant 64 caracteres ASCII imprimables.
Le nom vient de l'alphabet de 64 caracteres : A-Z, a-z, 0-9, + et /. = est utilise pour le padding.
Base64 n'est pas du chiffrement. Il ne fournit aucune securite.
The Base64 Alphabet (RFC 4648):
Index Char Index Char Index Char Index 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 character: =Comment fonctionne Base64
Le processus convertit chaque groupe de 3 octets en 4 caracteres :
- Prenez 3 octets (24 bits).
- Divisez en quatre groupes de 6 bits.
- Mappez chaque valeur au caractere Base64.
- Ajoutez du padding si necessaire.
Exemple avec la chaine "Hi!" :
Encoding "Hi!" step by step:
Step 1: Convert ASCII to binary
'H' = 72 = 01001000
'i' = 105 = 01101001
'!' = 33 = 00100001
Step 2: Concatenate all bits
01001000 01101001 00100001 (24 bits total)
Step 3: Split into 6-bit groups
010010 | 000110 | 100100 | 100001
18 6 36 33
Step 4: Map to Base64 alphabet
18 â S
6 â G
36 â k
33 â h
Result: "Hi!" â "SGkh"
âââââââââââââââââââââââââââââââââââââââââ
Encoding "Hi" (only 2 bytes - needs padding):
'H' = 01001000
'i' = 01101001
01001000 01101001 + 0000 (pad to 18 bits)
010010 | 000110 | 100100
18 6 36
18 â S, 6 â G, 36 â k, padding â =
Result: "Hi" â "SGk="Cas d'utilisation courants
Base64 apparait dans de nombreux domaines :
1. Data URIs
Integration de fichiers directement dans HTML/CSS :
<!-- Embedding a small PNG icon as a data URI -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB
CAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
alt="1x1 pixel" width="16" height="16" />
<!-- SVG data URI in CSS -->
<style>
.icon-arrow {
background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz
0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2
h0PSIyNCI+PHBhdGggZD0iTTEyIDRsLTEuNDEgMS40MUwxNi4xNyAxMUg0dj
JoMTIuMTdsLTUuNTggNS41OUwxMiAyMGw4LTh6Ii8+PC9zdmc+');
width: 24px;
height: 24px;
}
</style>
<!-- Inline font as data URI (for critical fonts) -->
@font-face {
font-family: 'CriticalFont';
src: url('data:font/woff2;base64,d09GMgABAAAAA...') format('woff2');
font-display: swap;
}2. Tokens JWT
Les JWT utilisent Base64URL pour encoder l'en-tete et le payload :
// JWT token structure: header.payload.signature
// Each part is Base64URL-encoded
const header = {
alg: "HS256",
typ: "JWT"
};
const payload = {
sub: "1234567890",
name: "Alice",
iat: 1516239022
};
// Base64URL encode (no padding, URL-safe chars)
function base64url(str) {
return btoa(str)
.replace(/\+/g, '-') // + â -
.replace(/\//g, '_') // / â _
.replace(/=+$/, ''); // remove padding
}
const encodedHeader = base64url(JSON.stringify(header));
// "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
const encodedPayload = base64url(JSON.stringify(payload));
// "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNTE2MjM5MDIyfQ"
// Final JWT: header.payload.signature
// eyJhbGci...IkpXVCJ9.eyJzdWIi...MjM5MDIyfQ.signature_here3. Authentification HTTP Basic
Le nom d'utilisateur et mot de passe sont encodes en Base64 :
// HTTP Basic Authentication
const username = 'admin';
const password = 'secret123';
// Encode credentials as Base64
const credentials = btoa(username + ':' + password);
// "YWRtaW46c2VjcmV0MTIz"
// Set the Authorization header
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Basic ' + credentials
// "Authorization: Basic YWRtaW46c2VjcmV0MTIz"
}
});
// Equivalent curl command:
// curl -H "Authorization: Basic YWRtaW46c2VjcmV0MTIz" https://api.example.com/data
// or simply:
// curl -u admin:secret123 https://api.example.com/data5. Secrets Kubernetes
Kubernetes stocke les secrets en Base64 dans les manifestes YAML.
# Kubernetes Secret manifest
apiVersion: v1
kind: Secret
metadata:
name: my-app-secrets
type: Opaque
data:
# Values must be Base64-encoded
# echo -n "mypassword" | base64 â bXlwYXNzd29yZA==
database-password: bXlwYXNzd29yZA==
# echo -n "sk-abc123xyz" | base64 â c2stYWJjMTIzeHl6
api-key: c2stYWJjMTIzeHl6
---
# Using stringData (Kubernetes encodes automatically)
apiVersion: v1
kind: Secret
metadata:
name: my-app-secrets-v2
type: Opaque
stringData:
# Plain text - Kubernetes handles Base64 encoding
database-password: mypassword
api-key: sk-abc123xyz6. Donnees binaires en JSON
Base64 est le standard pour inclure des donnees binaires dans JSON.
{
"document": {
"name": "report.pdf",
"content_type": "application/pdf",
"data": "JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL..."
},
"avatar": {
"format": "png",
"width": 128,
"height": 128,
"data": "iVBORw0KGgoAAAANSUhEUgAAAIAAAACA..."
}
}Base64 en JavaScript
JavaScript fournit btoa() et atob() pour le navigateur, Buffer pour Node.js :
// ========== Browser: btoa() and atob() ==========
// Encode ASCII string to Base64
const encoded = btoa('Hello, World!');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="
// Decode Base64 to ASCII string
const decoded = atob('SGVsbG8sIFdvcmxkIQ==');
console.log(decoded); // "Hello, World!"
// ========== Unicode strings (browser) ==========
// btoa() fails with non-ASCII characters
// btoa('Hello ') â Error!
// Solution: encode to UTF-8 first
function utf8ToBase64(str) {
return btoa(
encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
(_, p1) => String.fromCharCode(parseInt(p1, 16))
)
);
}
function base64ToUtf8(b64) {
return decodeURIComponent(
atob(b64).split('').map(c =>
'%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
).join('')
);
}
// Modern approach (using TextEncoder/TextDecoder)
function encodeBase64(str) {
const bytes = new TextEncoder().encode(str);
const binString = Array.from(bytes, b => String.fromCodePoint(b)).join('');
return btoa(binString);
}
function decodeBase64(b64) {
const binString = atob(b64);
const bytes = Uint8Array.from(binString, c => c.codePointAt(0));
return new TextDecoder().decode(bytes);
}
// ========== Node.js: Buffer ==========
// Encode string to Base64
const base64 = Buffer.from('Hello, World!').toString('base64');
console.log(base64); // "SGVsbG8sIFdvcmxkIQ=="
// Decode Base64 to string
const text = Buffer.from('SGVsbG8sIFdvcmxkIQ==', 'base64').toString('utf-8');
console.log(text); // "Hello, World!"
// Encode binary data (file) to Base64
const fs = require('fs');
const imageBase64 = fs.readFileSync('image.png').toString('base64');
const dataUri = 'data:image/png;base64,' + imageBase64;
// URL-safe Base64 in Node.js
const urlSafe = Buffer.from('Hello!').toString('base64url');
console.log(urlSafe); // "SGVsbG8h" (no padding, URL-safe chars)btoa() et atob() ne fonctionnent qu'avec l'ASCII. Pour l'Unicode, encodez d'abord en UTF-8.
Base64 en Python
Le module base64 de Python supporte Base64 standard et URL-safe :
import base64
# ========== Standard Base64 ==========
# Encode string to Base64
text = "Hello, World!"
encoded = base64.b64encode(text.encode('utf-8'))
print(encoded) # b'SGVsbG8sIFdvcmxkIQ=='
print(encoded.decode('ascii')) # "SGVsbG8sIFdvcmxkIQ=="
# Decode Base64 to string
decoded = base64.b64decode('SGVsbG8sIFdvcmxkIQ==')
print(decoded.decode('utf-8')) # "Hello, World!"
# ========== URL-Safe Base64 ==========
data = b'\xfb\xff\xfe' # bytes with +/- in standard Base64
standard = base64.b64encode(data) # b'+//+'
urlsafe = base64.urlsafe_b64encode(data) # b'-__-'
# Decode URL-safe Base64
decoded = base64.urlsafe_b64decode('-__-')
# ========== File encoding ==========
# Encode a file to Base64
with open('image.png', 'rb') as f:
file_base64 = base64.b64encode(f.read()).decode('ascii')
# Decode Base64 to a file
with open('output.png', 'wb') as f:
f.write(base64.b64decode(file_base64))
# ========== Working with JSON ==========
import json
payload = {
"name": "document.pdf",
"data": base64.b64encode(open('doc.pdf', 'rb').read()).decode('ascii')
}
json_str = json.dumps(payload)
# ========== Base32 and Base16 (Hex) ==========
base32 = base64.b32encode(b'Hello') # b'JBSWY3DP'
hex_encoded = base64.b16encode(b'Hello') # b'48656C6C6F'Base64 en ligne de commande
Linux/macOS et Windows fournissent des outils Base64 integres :
# ========== Linux / macOS ==========
# Encode a string
echo -n "Hello, World!" | base64
# SGVsbG8sIFdvcmxkIQ==
# Decode a Base64 string
echo "SGVsbG8sIFdvcmxkIQ==" | base64 --decode
# Hello, World!
# Encode a file
base64 image.png > image.b64
# or
cat image.png | base64 > image.b64
# Decode a file
base64 --decode image.b64 > image_restored.png
# Pipe from curl - encode API response
curl -s https://api.example.com/data | base64
# One-liner: create a data URI from an image
echo "data:image/png;base64,$(base64 < icon.png)" > data-uri.txt
# ========== macOS-specific ==========
# macOS base64 uses -D instead of --decode
echo "SGVsbG8=" | base64 -D
# ========== OpenSSL (cross-platform) ==========
echo -n "Hello" | openssl base64
echo "SGVsbG8=" | openssl base64 -d
# ========== Windows PowerShell ==========
# Encode
[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("Hello"))
# Decode
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("SGVsbG8="))Base64 URL-safe
Le Base64 standard utilise + et / qui ont une signification speciale dans les URLs.
| Caractere | Base64 standard | Base64 URL-safe |
|---|---|---|
| 62e | + | - (tiret) |
| 63e | / | _ (underscore) |
| Padding | = | Generalement omis |
Utilise dans les JWT, parametres URL et noms de fichiers.
// URL-Safe Base64 encoding/decoding
// JavaScript (browser)
function toBase64Url(str) {
return btoa(str)
.replace(/\+/g, '-') // Replace + with -
.replace(/\//g, '_') // Replace / with _
.replace(/=+$/, ''); // Remove padding
}
function fromBase64Url(b64url) {
// Restore standard Base64
let b64 = b64url
.replace(/-/g, '+') // Restore +
.replace(/_/g, '/'); // Restore /
// Add padding if needed
while (b64.length % 4 !== 0) {
b64 += '=';
}
return atob(b64);
}
// Node.js (built-in support)
const encoded = Buffer.from('Hello!').toString('base64url');
// "SGVsbG8h"
const decoded = Buffer.from('SGVsbG8h', 'base64url').toString();
// "Hello!"
// Python
import base64
encoded = base64.urlsafe_b64encode(b'Hello!').rstrip(b'=')
# b'SGVsbG8h'
decoded = base64.urlsafe_b64decode(b'SGVsbG8h' + b'==')
# b'Hello!'Considerations de performance
Base64 a des implications de performance :
33% de surcharge en taille.
Cout CPU pour l'encodage/decodage.
Mauvaise compression des donnees Base64.
Limites Data URI : uniquement pour les images < 5KB.
Alternative : multipart form data pour les gros fichiers.
Base64 Size Overhead Examples:
Original Size Base64 Size Overhead
âââââââââââââââââââââââââââââââââââââââââ
1 KB 1.37 KB +37%
10 KB 13.7 KB +37%
100 KB 137 KB +37%
1 MB 1.37 MB +37%
10 MB 13.7 MB +37%
Note: Actual overhead varies slightly due to
padding and line breaks (MIME uses 76-char lines).
Best practice thresholds:
< 5 KB â Data URI (inline) is fine
5-10 KB â Consider external file
> 10 KB â Always use external file/binary transferQuand ne pas utiliser Base64
Evitez Base64 dans ces situations :
- Gros fichiers : multipart/form-data
- Securite : AES, RSA
- Grandes images en HTML : balise img avec cache
- Stockage : BLOB en base de donnees
Questions frequentes
A quoi sert l'encodage Base64 ?
Base64 convertit les donnees binaires en texte pour une transmission sure. Utilise pour les Data URIs, JWT, authentification HTTP et MIME.
Comment encoder en Base64 en JavaScript ?
btoa() pour encoder, atob() pour decoder. Buffer.from() en Node.js.
Base64 est-il du chiffrement ?
Non. Base64 est un encodage, pas du chiffrement. Utilisez AES ou RSA pour la securite.
Pourquoi Base64 augmente la taille de 33% ?
3 octets deviennent 4 caracteres (4/3 = 1.333 soit 33% de plus).
Quelle difference entre Base64 et Base64URL ?
Base64URL remplace + par - et / par _ pour etre compatible avec les URLs.
L'encodage Base64 est un outil fondamental. Utilisez notre outil en ligne pour l'encodage et le decodage rapides.
Encodez et decodez Base64 avec notre outil gratuit.
Related Developer Tools and Guides
- Base64 Encoder / Decoder - Encode and decode Base64 strings online
- Image to Base64 Converter - Convert images to Base64 data URIs
- JWT Decoder - Decode and inspect JWT tokens
- Base64 Real-World Uses - 7 practical Base64 use cases
- Base64 Command Line Guide - Encode and decode Base64 in the terminal
- Base64 Image Embedding - Embed Base64 images in HTML and CSS
- JWT Token Explained - Understanding JSON Web Tokens
- API Authentication Guide - OAuth, JWT, and API key patterns