Base64 Encoding: Quando e Perche Usarlo

THEJORD Team5 min di lettura
base64encodingdevelopmentsecuritytools

Base64 encoding: cos'è, come funziona e quando usarlo. Guida completa per codificare immagini, file binari e dati in stringhe di testo portabili oggi.

Base64 Encoding: Quando e Perche Usarlo

Cos'è Base64

Base64 è uno schema di codifica che converte dati binari in una rappresentazione testuale usando 64 caratteri ASCII sicuri. È fondamentale per trasmettere dati binari attraverso canali che supportano solo testo, come email (MIME), URL, JSON, e header HTTP. Questa guida spiega quando e come usare Base64 correttamente, con esempi pratici in diversi linguaggi.

Come Funziona

L'Alfabeto Base64

# I 64 caratteri usati:
A-Z (26) + a-z (26) + 0-9 (10) + +/ (2) = 64 caratteri

# Tabella indice → carattere
0-25:  A-Z
26-51: a-z
52-61: 0-9
62:    +
63:    /

# Padding: = (usato per allineare a multipli di 4)

Processo di Codifica

# Input: "Hi" (2 byte = 16 bit)
# Binario: 01001000 01101001

# 1. Raggruppa in blocchi di 6 bit
# 010010 | 000110 | 1001XX
# (padding con 00 per completare)
# 010010 | 000110 | 100100

# 2. Converti ogni gruppo in decimale
# 18 | 6 | 36

# 3. Mappa all'alfabeto Base64
# S | G | k

# 4. Aggiungi padding per multipli di 4
# SGk=

# Risultato: "Hi" → "SGk="

Overhead di Dimensione

# Base64 aumenta la dimensione del ~33%

# Perché?
# - 3 byte input → 4 caratteri output
# - 8 bit × 3 = 24 bit → 6 bit × 4 = 24 bit
# - Rapporto: 4/3 = 1.33 (33% overhead)

# Esempi pratici:
# File 1 MB → ~1.33 MB in Base64
# Immagine 100 KB → ~133 KB in Base64

Codifica in JavaScript

Browser (btoa/atob)

// Codifica stringa → Base64
const encoded = btoa('Hello World');
console.log(encoded);  // "SGVsbG8gV29ybGQ="

// Decodifica Base64 → stringa
const decoded = atob('SGVsbG8gV29ybGQ=');
console.log(decoded);  // "Hello World"

// ATTENZIONE: btoa/atob funzionano solo con ASCII!
// Per Unicode usa TextEncoder/TextDecoder

// Codifica Unicode
function encodeUnicode(str) {
  const bytes = new TextEncoder().encode(str);
  const binString = Array.from(bytes, b => String.fromCharCode(b)).join('');
  return btoa(binString);
}

// Decodifica Unicode
function decodeUnicode(base64) {
  const binString = atob(base64);
  const bytes = Uint8Array.from(binString, c => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

// Esempio con emoji
const emoji = encodeUnicode('Ciao 👋');
console.log(emoji);  // "Q2lhbyDwn5GL"

Node.js (Buffer)

// Codifica
const encoded = Buffer.from('Hello World').toString('base64');
console.log(encoded);  // "SGVsbG8gV29ybGQ="

// Decodifica
const decoded = Buffer.from('SGVsbG8gV29ybGQ=', 'base64').toString('utf8');
console.log(decoded);  // "Hello World"

// File → Base64
const fs = require('fs');
const imageBase64 = fs.readFileSync('image.png').toString('base64');

// Base64 → File
const buffer = Buffer.from(imageBase64, 'base64');
fs.writeFileSync('output.png', buffer);

// URL-safe Base64 (no +/)
const urlSafe = encoded
  .replace(/\+/g, '-')
  .replace(/\//g, '_')
  .replace(/=/g, '');

Codifica in Python

import base64

# Codifica stringa
text = 'Hello World'
encoded = base64.b64encode(text.encode()).decode()
print(encoded)  # "SGVsbG8gV29ybGQ="

# Decodifica
decoded = base64.b64decode(encoded).decode()
print(decoded)  # "Hello World"

# File → Base64
with open('image.png', 'rb') as f:
    image_base64 = base64.b64encode(f.read()).decode()

# Base64 → File
with open('output.png', 'wb') as f:
    f.write(base64.b64decode(image_base64))

# URL-safe Base64
url_safe = base64.urlsafe_b64encode(text.encode()).decode()
# Usa - invece di + e _ invece di /

Casi d'Uso Comuni

Data URL per Immagini

// Inline immagini in HTML/CSS senza richieste HTTP


// CSS
.icon {
  background-image: url('data:image/svg+xml;base64,PHN2Zy...');
}

// JavaScript - converti immagine a Data URL
function imageToDataUrl(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.readAsDataURL(file);
  });
}

// Uso con input file
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async (e) => {
  const dataUrl = await imageToDataUrl(e.target.files[0]);
  console.log(dataUrl);  // "data:image/jpeg;base64,/9j/4AAQ..."
});

Basic Authentication

// HTTP Basic Auth usa Base64
const username = 'user';
const password = 'pass123';
const credentials = btoa(`${username}:${password}`);

// Header HTTP
const headers = {
  'Authorization': `Basic ${credentials}`
};

// Fetch con auth
fetch('https://api.example.com/data', { headers });

// NOTA: Basic Auth NON è crittografia!
// Il server può decodificare facilmente
// Usa sempre HTTPS

JSON con Dati Binari

// JSON non supporta dati binari direttamente
// Base64 è la soluzione standard

// Invio file via API
const fileBuffer = await file.arrayBuffer();
const base64File = btoa(
  new Uint8Array(fileBuffer).reduce(
    (data, byte) => data + String.fromCharCode(byte), ''
  )
);

const payload = {
  filename: 'document.pdf',
  content: base64File,
  mimeType: 'application/pdf'
};

await fetch('/api/upload', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(payload)
});

JWT (JSON Web Tokens)

// JWT usa Base64URL (variante URL-safe)
// Struttura: header.payload.signature

const jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

// Decodifica payload (parte centrale)
function decodeJwtPayload(jwt) {
  const base64Url = jwt.split('.')[1];
  const base64 = base64Url
    .replace(/-/g, '+')
    .replace(/_/g, '/');
  const payload = atob(base64);
  return JSON.parse(payload);
}

const payload = decodeJwtPayload(jwt);
// { sub: "1234567890", name: "John Doe", iat: 1516239022 }

Quando NON Usare Base64

Non è Crittografia

// SBAGLIATO: nascondere password
const password = btoa('secret123');
// Chiunque può decodificare!

// CORRETTO: usa hash per password
const bcrypt = require('bcrypt');
const hashedPassword = await bcrypt.hash('secret123', 10);

// CORRETTO: usa encryption per dati sensibili
const crypto = require('crypto');
// ... usa AES o altro algoritmo di encryption

Non per File Grandi

// SBAGLIATO: immagini grandi inline

// Aumenta HTML, non cacheable, lento

// CORRETTO: usa URL normale

// Cacheable, streaming, dimensione ottimale

// REGOLA: Base64 solo per file < 10KB

Varianti di Base64

Base64 Standard vs URL-Safe

// Standard (RFC 4648)
Alfabeto: A-Z, a-z, 0-9, +, /
Padding: =

// URL-Safe (RFC 4648 §5)
Alfabeto: A-Z, a-z, 0-9, -, _
Padding: opzionale (spesso omesso)

// Conversione
function toUrlSafe(base64) {
  return base64
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
}

function fromUrlSafe(base64url) {
  let base64 = base64url
    .replace(/-/g, '+')
    .replace(/_/g, '/');

  // Aggiungi padding
  while (base64.length % 4) {
    base64 += '=';
  }
  return base64;
}

Base32 e Base16

# Altre codifiche simili

# Base32 (RFC 4648)
# Alfabeto: A-Z, 2-7 (32 caratteri)
# Uso: OTP, codici case-insensitive
# Overhead: 60%

# Base16 (Hex)
# Alfabeto: 0-9, A-F (16 caratteri)
# Uso: hash, colori, debug
# Overhead: 100%

# Confronto dimensioni (100 byte input)
# Base64: ~133 byte
# Base32: ~160 byte
# Base16: 200 byte

Performance Tips

// Streaming per file grandi
const { Readable } = require('stream');
const { createHash } = require('crypto');

async function streamToBase64(readable) {
  const chunks = [];
  for await (const chunk of readable) {
    chunks.push(chunk);
  }
  return Buffer.concat(chunks).toString('base64');
}

// Evita conversioni non necessarie
// LENTO
const str = buffer.toString('utf8');
const base64 = Buffer.from(str).toString('base64');

// VELOCE
const base64 = buffer.toString('base64');

Strumenti Online

Per codifica/decodifica rapida:

Conclusione

Base64 è essenziale quando devi:

  • Trasmettere binari in JSON/XML: API, configurazioni
  • Inline piccole risorse: Icone SVG, favicon
  • Autenticazione HTTP: Basic auth header
  • Token: JWT, session token

Ricorda: Base64 NON è encryption, aumenta la dimensione del 33%, e non è adatto per file grandi.

Per altri strumenti utili, esplora i nostri tool online gratuiti. Per la specifica completa, consulta RFC 4648.