DevToolBoxGRATIS
Blog

Base64 codering en decodering: Complete ontwikkelaarsgids

10 min lezenby DevToolBox

Base64 encoding is one of the most widely used data encoding schemes in software development. From embedding images in HTML and CSS to transmitting binary data through text-based protocols like HTTP and SMTP, Base64 is everywhere. This comprehensive guide explains how Base64 works at the bit level, covers all major use cases, provides working code examples in JavaScript, Python, and the command line, and discusses URL-safe Base64, performance considerations, and when to avoid Base64 altogether.

Encode and decode Base64 instantly with our free online tool.

What Is Base64 Encoding?

Base64 is a binary-to-text encoding scheme that represents binary data using 64 printable ASCII characters. It was designed to safely transmit binary data through systems that only support text, such as email (MIME), URLs, and JSON payloads.

The name "Base64" comes from the fact that it uses a 64-character alphabet: A-Z (26), a-z (26), 0-9 (10), + (1), and / (1). The = character is used for padding. Every 3 bytes of input data produces exactly 4 Base64 characters, which means Base64-encoded data is approximately 33% larger than the original.

Base64 is not encryption. It provides no security whatsoever. Anyone can decode Base64 data without a key. Its purpose is purely encoding: converting binary data into a text-safe format.

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: =

How Base64 Works: Step-by-Step

The Base64 encoding process converts every group of 3 input bytes (24 bits) into 4 output characters (6 bits each). Here is the step-by-step process:

  1. Take 3 bytes of input data (24 bits total).
  2. Split these 24 bits into four 6-bit groups.
  3. Map each 6-bit value (0-63) to its corresponding character in the Base64 alphabet.
  4. If the input length is not a multiple of 3, add padding (=) to make the output length a multiple of 4.

Let us trace through encoding the string "Hi!" as an example:

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="

Common Use Cases for Base64

Base64 encoding appears in many areas of web development and software engineering:

1. Data URIs (Embedding Images in HTML/CSS)

Data URIs allow you to embed small files directly in HTML or CSS, eliminating an HTTP request. This is especially useful for small icons, SVGs, and fonts:

<!-- 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. JWT Tokens (JSON Web Tokens)

JWTs use Base64URL encoding (a URL-safe variant) to encode the header and payload segments. The token format is header.payload.signature, where header and payload are Base64URL-encoded JSON:

// 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_here

3. API Authentication (HTTP Basic Auth)

HTTP Basic Authentication encodes the username and password as a Base64 string in the Authorization header:

// 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/data

5. Kubernetes Secrets

Kubernetes stores secret values as Base64-encoded strings in YAML manifests. This is not for security (Kubernetes secrets are not encrypted by default) but for safely storing binary data in 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-abc123xyz

6. Storing Binary Data in JSON

JSON does not support binary data natively. When you need to include binary data (images, files, certificates) in a JSON payload, Base64 encoding is the standard approach:

{
  "document": {
    "name": "report.pdf",
    "content_type": "application/pdf",
    "data": "JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL..."
  },
  "avatar": {
    "format": "png",
    "width": 128,
    "height": 128,
    "data": "iVBORw0KGgoAAAANSUhEUgAAAIAAAACA..."
  }
}

Base64 in JavaScript

JavaScript provides built-in functions for Base64 encoding and decoding in both browser and Node.js environments:

// ========== 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)

Important notes: btoa() and atob() only work with ASCII strings in browsers. For Unicode text, you need to encode to UTF-8 first. Node.js uses the Buffer class which handles binary data natively.

Base64 in Python

Python provides the base64 module in its standard library with support for standard Base64, URL-safe Base64, and Base32/Base16 encoding:

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 on the Command Line

Both Linux/macOS and Windows provide built-in Base64 encoding and decoding tools:

# ========== 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="))

URL-Safe Base64 Encoding

Standard Base64 uses + and / characters which have special meaning in URLs. URL-safe Base64 (also called Base64URL, defined in RFC 4648) replaces these:

CharacterStandard Base64URL-Safe Base64
62nd char+- (hyphen)
63rd char/_ (underscore)
Padding=Usually omitted

URL-safe Base64 is used in JWT tokens, URL parameters, filename-safe encoding, and anywhere Base64 data appears in URLs or filenames.

// 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!'

Performance Considerations

While Base64 is ubiquitous, it has performance implications you should be aware of:

33% size overhead: Every 3 bytes become 4 characters. A 1MB image becomes ~1.37MB when Base64-encoded. For large files, this overhead is significant.

CPU cost: Encoding and decoding require processing every byte. For bulk operations (thousands of files), consider binary transfer methods instead.

No compression: Base64-encoded data does not compress well because the encoding destroys the patterns that compression algorithms rely on. Always compress before encoding, not after.

Data URI limits: While modern browsers support large data URIs, embedding large Base64 images in HTML increases page weight and blocks rendering. Use data URIs only for images under 5KB.

Alternative for large files: For files over 10KB, use proper binary transfer (multipart form data, binary WebSocket frames, or direct file downloads) instead of Base64.

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 transfer

When NOT to Use Base64

Base64 is not always the right choice. Avoid it in these situations:

  • Large file transfers: Use multipart/form-data or binary protocols instead
  • Security/encryption: Base64 is not encryption. Use AES, RSA, or similar algorithms
  • Large images in HTML: Use regular <img> tags with proper caching headers
  • Database storage: Most databases support BLOB types for binary data
  • When bandwidth matters: The 33% overhead adds up on metered connections

Frequently Asked Questions

What is Base64 encoding used for?

Base64 encoding converts binary data to text so it can be safely transmitted through text-only systems. Common uses include embedding images in HTML/CSS (data URIs), JWT tokens, HTTP Basic authentication, email attachments (MIME), Kubernetes secrets, and storing binary data in JSON.

How do I Base64 encode a string in JavaScript?

In the browser, use btoa() to encode and atob() to decode ASCII strings. For Unicode strings, encode to UTF-8 first: btoa(unescape(encodeURIComponent(str))). In Node.js, use Buffer.from(str).toString("base64") to encode and Buffer.from(b64, "base64").toString() to decode.

Is Base64 encoding the same as encryption?

No. Base64 is an encoding scheme, not encryption. Anyone can decode Base64 data without a key. It provides zero security. For security, use proper encryption algorithms like AES or RSA. Base64 is only for converting binary data to a text-safe format.

Why does Base64 make data 33% larger?

Base64 represents each group of 3 bytes (24 bits) as 4 characters (6 bits each). Since 4/3 = 1.333, the output is 33% larger. Additionally, padding characters (=) may add a few extra bytes. This overhead is the trade-off for text-safe binary representation.

What is the difference between Base64 and Base64URL?

Standard Base64 uses + and / which have special meaning in URLs. Base64URL replaces + with - (hyphen) and / with _ (underscore), and usually omits the = padding. Base64URL is used in JWT tokens, URL parameters, and filenames where + and / would cause issues.

Base64 encoding is a fundamental tool in every developer's toolkit. It bridges the gap between binary data and text-based systems, enabling data URIs, JWT tokens, API authentication, and email attachments. Understanding how it works at the bit level, knowing when to use URL-safe variants, and being aware of the 33% size overhead will help you use Base64 effectively. For quick encoding and decoding, try our free online tool.

Encode and decode Base64 with our free online tool.

Related Developer Tools and Guides

𝕏 Twitterin LinkedIn
Was dit nuttig?

Blijf op de hoogte

Ontvang wekelijkse dev-tips en nieuwe tools.

Geen spam. Altijd opzegbaar.

Try These Related Tools

B64Base64 Encoder/DecoderπŸ–ΌοΈImage Base64 ConverterJWTJWT DecoderBβ†’Base64 Encoder

Related Articles

Base64 Encoding in Praktijk: 7 Gebruiken die Elke Ontwikkelaar Moet Kennen

Ontdek 7 praktische toepassingen van Base64: embedded images, Kubernetes secrets, JWT-tokens en data URIs.

Base64 Encode & Decode via de opdrachtregel (Linux, Mac, Windows)

Base64-strings coderen en decoderen in de terminal.

Base64 afbeeldingen insluiten in HTML, CSS & email: Complete gids

Sluit afbeeldingen in als Base64 data URI in HTML, CSS en email.