DevToolBoxGRÁTIS
Blog

Base64 Encode & Decode: Guia Completo com Exemplos de Código

12 min de leituraby DevToolBox

Base64 encoding is one of the most fundamental data encoding schemes in computing. Every day, millions of developers use base64 encode and base64 decode operations to embed images in HTML, transmit binary data over text-based protocols, and handle authentication tokens. Whether you need a quick base64 encoder for a one-off task or want to understand the algorithm deeply, this comprehensive guide covers everything from the underlying 6-bit mapping to practical code examples in JavaScript, Python, Bash, and PowerShell. If you are looking to base64 encode decode online, our free tool makes it instant.

Try our free online Base64 Encode/Decode tool instantly.

What Is Base64 Encoding?

Base64 is a binary-to-text encoding scheme that represents binary data using a set of 64 printable ASCII characters. The name "Base64" comes from the fact that it uses a 64-character alphabet: A-Z (26 characters), a-z (26 characters), 0-9 (10 characters), and two additional symbols + and /. A 65th character, =, is used for padding. The base64 encoder processes input data in groups of 3 bytes (24 bits) and converts them into 4 Base64 characters (4 x 6 bits = 24 bits).

The algorithm works by taking every three bytes of input and splitting them into four 6-bit groups. Each 6-bit value (ranging from 0 to 63) maps to one character in the Base64 alphabet. When the input length is not a multiple of three, the encoder adds = padding characters to ensure the output length is always a multiple of four. One byte of remainder produces two Base64 characters followed by ==, while two bytes of remainder produce three Base64 characters followed by =.

Base64 encoding increases data size by approximately 33% (a ratio of 4:3). This overhead is the trade-off for being able to safely transmit binary data through text-only channels such as email, JSON, XML, and URL query parameters. Despite the size increase, base64 encode remains the standard choice because it is simple, universally supported, and does not require escaping special characters.

How Base64 Encode/Decode Works

Let us walk through the base64 encode process step by step, converting the ASCII string Man into Base64:

  1. Convert to ASCII bytes: M = 77 (01001101), a = 97 (01100001), n = 110 (01101110).
  2. Concatenate the bits: 01001101 01100001 01101110 (24 bits total).
  3. Split into 6-bit groups: 010011 | 010110 | 000101 | 101110.
  4. Convert each 6-bit value to decimal: 19, 22, 5, 46.
  5. Map to Base64 characters using the alphabet table: 19 = T, 22 = W, 5 = F, 46 = u.

The result is TWFu. To base64 decode this string, reverse the process: look up each character in the table to get 6-bit values, concatenate all bits, and split back into 8-bit bytes to recover the original data.

Padding example: Encoding Ma (only 2 bytes = 16 bits) produces the bit string 01001101 01100001. We need 18 bits (three 6-bit groups) for three Base64 characters, so two zero bits are appended: 010011 | 010110 | 000100. This maps to TWE plus one = padding, giving the final result TWE=. For a single byte M, the result is TQ== with two padding characters.

Common Base64 Use Cases

Base64 encoding appears everywhere in modern software development. Here are the most important use cases:

Data URIs (Base64 encode image): You can embed images directly in HTML or CSS using data URIs like data:image/png;base64,iVBOR.... This eliminates extra HTTP requests for small images such as icons, logos, and thumbnails. To base64 encode image files, you convert the binary image data to a Base64 string and embed it inline. This technique is widely used for email signatures, single-page applications, and CSS sprites.

Email attachments (MIME): The MIME standard uses Base64 to encode binary attachments in email messages. Since email protocols (SMTP) were originally designed to transmit 7-bit ASCII text, binary files like images, PDFs, and documents must be Base64-encoded before being included as attachments. The Content-Transfer-Encoding: base64 header tells the email client to decode the data.

API authentication (HTTP Basic Auth): HTTP Basic Authentication encodes the username:password pair using Base64 and sends it in the Authorization: Basic dXNlcjpwYXNz header. While Base64 is not encryption (it is trivially reversible), it ensures the credentials are safely transmitted as ASCII text. Always use HTTPS to protect Base64-encoded credentials in transit.

JSON Web Tokens (JWT): JWTs consist of three Base64URL-encoded segments separated by dots: header.payload.signature. The header and payload are JSON objects that are Base64URL-encoded (not encrypted) to form a compact, URL-safe token. Developers frequently need to base64 decode JWT segments for debugging and inspection.

URL-safe data transfer: When you need to pass binary or structured data through URLs, cookies, or query parameters, Base64 encoding ensures the data contains only safe ASCII characters. Base64URL (a variant using - and _ instead of + and /) is specifically designed for URL contexts.

Base64 Encode/Decode Code Examples

JavaScript Base64 Encode/Decode

In the browser, javascript base64 encode is done with btoa() and decoding with atob(). For Node.js, use the Buffer class. Note that btoa() only handles Latin-1 characters; for Unicode strings, you need to encode to UTF-8 first:

// ===== Browser: btoa() and atob() =====

// Base64 encode a string
const encoded = btoa('Hello World');
console.log(encoded); // "SGVsbG8gV29ybGQ="

// Base64 decode a string
const decoded = atob('SGVsbG8gV29ybGQ=');
console.log(decoded); // "Hello World"

// Handle Unicode strings (btoa only supports Latin-1)
function base64EncodeUnicode(str) {
  return btoa(encodeURIComponent(str).replace(
    /%([0-9A-F]{2})/g,
    (_, p1) => String.fromCharCode(parseInt(p1, 16))
  ));
}

function base64DecodeUnicode(str) {
  return decodeURIComponent(
    Array.from(atob(str))
      .map(c => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))
      .join('')
  );
}

base64EncodeUnicode('Hello 🌍');  // "SGVsbG8g8J+MjQ=="
base64DecodeUnicode('SGVsbG8g8J+MjQ=='); // "Hello 🌍"

// ===== Node.js: Buffer =====

// Encode
const buf = Buffer.from('Hello World', 'utf-8');
const b64 = buf.toString('base64');
console.log(b64); // "SGVsbG8gV29ybGQ="

// Decode
const original = Buffer.from(b64, 'base64').toString('utf-8');
console.log(original); // "Hello World"

// URL-safe Base64 in Node.js
const urlSafe = buf.toString('base64url');
console.log(urlSafe); // "SGVsbG8gV29ybGQ"

Python Base64 Encode/Decode

In Python, python base64 encode uses the built-in base64 module. The module provides functions for standard Base64, URL-safe Base64, and other variants:

import base64

# Standard Base64 encode
text = "Hello World"
encoded = base64.b64encode(text.encode('utf-8'))
print(encoded)          # b'SGVsbG8gV29ybGQ='
print(encoded.decode())  # "SGVsbG8gV29ybGQ="

# Standard Base64 decode
decoded = base64.b64decode(encoded)
print(decoded.decode('utf-8'))  # "Hello World"

# URL-safe Base64 (replaces + with - and / with _)
url_encoded = base64.urlsafe_b64encode(text.encode('utf-8'))
print(url_encoded.decode())  # "SGVsbG8gV29ybGQ="

url_decoded = base64.urlsafe_b64decode(url_encoded)
print(url_decoded.decode('utf-8'))  # "Hello World"

# Encode a file (e.g., an image)
with open('image.png', 'rb') as f:
    image_b64 = base64.b64encode(f.read()).decode('utf-8')
    data_uri = f"data:image/png;base64,{image_b64}"

# Decode Base64 back to file
with open('output.png', 'wb') as f:
    f.write(base64.b64decode(image_b64))

Bash / Linux Base64 Encode/Decode

On Linux and macOS, bash base64 encode uses the base64 command-line utility. This is the simplest way to linux base64 encode data from the terminal:

# Base64 encode a string (Linux)
echo -n "Hello World" | base64
# Output: SGVsbG8gV29ybGQ=

# Base64 decode a string (Linux)
echo "SGVsbG8gV29ybGQ=" | base64 --decode
# Output: Hello World

# macOS uses -D instead of --decode
echo "SGVsbG8gV29ybGQ=" | base64 -D
# Output: Hello World

# Base64 encode a file
base64 image.png > image_b64.txt

# Base64 decode a file
base64 --decode image_b64.txt > restored_image.png

# Encode and use inline (e.g., for curl auth header)
AUTH=$(echo -n "user:password" | base64)
curl -H "Authorization: Basic $AUTH" https://api.example.com/data

# Pipe from/to files
cat document.pdf | base64 > document_b64.txt
cat document_b64.txt | base64 --decode > restored.pdf

# Wrap lines at 76 characters (MIME standard)
echo -n "Long text..." | base64 -w 76

PowerShell Base64 Encode/Decode

In Windows PowerShell, powershell base64 encode uses the .NET [Convert] class. PowerShell works with UTF-16LE encoding by default:

# PowerShell Base64 encode (UTF-16LE by default)
$text = "Hello World"
$bytes = [System.Text.Encoding]::UTF8.GetBytes($text)
$encoded = [Convert]::ToBase64String($bytes)
Write-Output $encoded
# Output: SGVsbG8gV29ybGQ=

# PowerShell Base64 decode
$decoded = [Convert]::FromBase64String($encoded)
$original = [System.Text.Encoding]::UTF8.GetString($decoded)
Write-Output $original
# Output: Hello World

# Encode a file to Base64
$fileBytes = [IO.File]::ReadAllBytes("C:\image.png")
$fileBase64 = [Convert]::ToBase64String($fileBytes)

# Decode Base64 to file
$decodedBytes = [Convert]::FromBase64String($fileBase64)
[IO.File]::WriteAllBytes("C:\restored.png", $decodedBytes)

# One-liner for encoding strings (UTF-8)
[Convert]::ToBase64String(
  [Text.Encoding]::UTF8.GetBytes("Hello World")
)

# Using UTF-16LE (default Windows encoding)
$utf16 = [Convert]::ToBase64String(
  [Text.Encoding]::Unicode.GetBytes("Hello World")
)
# Note: UTF-16LE produces different output than UTF-8

Base64 Encoding Table

The complete Base64 alphabet maps each 6-bit value (0-63) to a printable ASCII character. This is the standard table defined in RFC 4648:

ValueCharValueCharValueCharValueChar
0A16Q32g48w
1B17R33h49x
2C18S34i50y
3D19T35j51z
4E20U36k520
5F21V37l531
6G22W38m542
7H23X39n553
8I24Y40o564
9J25Z41p575
10K26a42q586
11L27b43r597
12M28c44s608
13N29d45t619
14O30e46u62+
15P31f47v63/

Padding: =

Base64 URL-Safe Encoding

Standard Base64 uses + and / characters which have special meanings in URLs. Base64URL encoding replaces these with URL-safe alternatives: + becomes - (hyphen) and / becomes _ (underscore). Additionally, the = padding is typically omitted since the data length can be inferred.

Base64URL is defined in RFC 4648 Section 5 and is the encoding used in JSON Web Tokens (JWT), OAuth 2.0 PKCE code verifiers, and many modern APIs. When you base64 encode data for use in URLs, query parameters, or filenames, always use the URL-safe variant to avoid encoding issues.

Here is a comparison of standard Base64 vs Base64URL encoding:

// Standard Base64 vs Base64URL comparison

// Standard Base64 (RFC 4648 Section 4)
// Alphabet: A-Z, a-z, 0-9, +, /
// Padding:  = (required)
"Hello World?" → "SGVsbG8gV29ybGQ/"   // contains /
"subjects?"    → "c3ViamVjdHM/"       // contains /
"<<???>>"     → "PDw/Pz8+Pg=="        // contains + and =

// Base64URL (RFC 4648 Section 5)
// Alphabet: A-Z, a-z, 0-9, -, _
// Padding:  omitted (optional)
"Hello World?" → "SGVsbG8gV29ybGQ_"   // / replaced with _
"subjects?"    → "c3ViamVjdHM_"       // / replaced with _
"<<???>>"     → "PDw_Pz8-Pg"          // + → -, / → _, no padding

// JavaScript conversion between formats
function base64ToBase64Url(base64) {
  return base64
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}

function base64UrlToBase64(base64url) {
  let base64 = base64url
    .replace(/-/g, '+')
    .replace(/_/g, '/');
  // Add padding
  while (base64.length % 4 !== 0) {
    base64 += '=';
  }
  return base64;
}

Base64 Image Encoding

One of the most popular uses of Base64 is embedding images directly in HTML and CSS. When you base64 encode image files, you create a data URI that can replace an image URL. The format is: data:[media-type];base64,[encoded-data].

Common use cases for base64 encode image include: inline images in HTML emails (where external URLs may be blocked), small icons and UI elements embedded directly in CSS (eliminating HTTP requests), embedding images in JSON API responses, and bundling assets in single-page applications.

Performance considerations: Base64-encoded images are approximately 33% larger than the original binary files. For images larger than a few kilobytes, it is usually more efficient to serve them as separate files with proper caching headers. Base64 embedding is best for small images (under 10KB), inline SVGs, and situations where reducing HTTP requests is critical.

Using Base64 images in HTML:

<!-- Inline Base64 image in HTML -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAADElEQVQI12P4//8/AwAI/AL+hc2rNAAAAABJRU5E
rkJggg==" alt="Red dot" width="5" height="5" />

<!-- Base64 SVG in HTML -->
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDov
L3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMT
AwIj48Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI0MCIgZmlsbD0icmVk
Ii8+PC9zdmc+" alt="Red circle" />

<!-- Base64 favicon -->
<link rel="icon" href="data:image/x-icon;base64,AAABAA..." />

Using Base64 images in CSS:

/* Base64 background image in CSS */
.icon-check {
  background-image: url('data:image/svg+xml;base64,PHN2ZyB4bW...');
  background-size: contain;
  width: 24px;
  height: 24px;
}

/* Base64 cursor in CSS */
.custom-cursor {
  cursor: url('data:image/png;base64,iVBORw0KGgo...'), auto;
}

/* Base64 font in CSS (@font-face) */
@font-face {
  font-family: 'CustomFont';
  src: url('data:font/woff2;base64,d09GMgABAAAAAD...') format('woff2');
}

Converting an image to Base64 in JavaScript (browser):

// Convert image file to Base64 data URI (browser)
function imageToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// Usage with file input
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async (e) => {
  const file = e.target.files[0];
  const dataUri = await imageToBase64(file);
  console.log(dataUri);
  // "data:image/png;base64,iVBORw0KGgo..."
});

// Convert canvas to Base64
const canvas = document.getElementById('myCanvas');
const base64Image = canvas.toDataURL('image/png');
// "data:image/png;base64,iVBORw0KGgo..."

// Node.js: encode image file to Base64
const fs = require('fs');
const imageBuffer = fs.readFileSync('photo.jpg');
const base64String = imageBuffer.toString('base64');
const dataUri = `data:image/jpeg;base64,${base64String}`;

Frequently Asked Questions

What is Base64 encoding used for?

Base64 encoding is used to convert binary data into ASCII text so it can be safely transmitted over text-based protocols. The most common use cases include: embedding images in HTML/CSS via data URIs, encoding email attachments (MIME), transmitting binary data in JSON/XML APIs, HTTP Basic Authentication headers, JSON Web Tokens (JWT), and storing binary data in text-only databases or configuration files. Base64 encoding ensures that binary data is not corrupted during transport through systems that only support ASCII text.

How do I Base64 encode a string in JavaScript?

In the browser, use btoa() to Base64 encode a string: btoa("Hello World") returns "SGVsbG8gV29ybGQ=". For decoding, use atob("SGVsbG8gV29ybGQ=") which returns "Hello World". For Unicode strings, first encode to UTF-8: btoa(unescape(encodeURIComponent(text))). In Node.js, use Buffer.from("Hello World").toString("base64") for encoding, and Buffer.from(encoded, "base64").toString("utf-8") for decoding.

Is Base64 encoding the same as encryption?

No, Base64 encoding is NOT encryption. Base64 is a reversible encoding scheme that anyone can decode without a key. It provides zero security and should never be used to protect sensitive data. Base64 simply converts binary data to text format for safe transport. If you need to protect data, use proper encryption algorithms like AES-256 or RSA. Base64 is often confused with encryption because encoded strings look unreadable, but they can be decoded instantly by anyone.

Base64 encoding is a foundational skill for every developer. From embedding images in data URIs to debugging JWT tokens, understanding how to base64 encode and base64 decode data is essential for modern web development. Bookmark this guide for quick reference, and use our free online tool for instant encoding and decoding.

Base64 encode and decode strings instantly with our free online tool.

𝕏 Twitterin LinkedIn
Isso foi útil?

Fique atualizado

Receba dicas de dev e novos ferramentas semanalmente.

Sem spam. Cancele a qualquer momento.

Try These Related Tools

B64Base64 Encoder/DecoderB→Base64 Encoder→BBase64 DecoderJWTJWT Decoder

Related Articles

Base64 em Prática: 7 Usos que Todo Desenvolvedor Deve Conhecer

Descubra 7 usos práticos de Base64: imagens em HTML, segredos Kubernetes, tokens JWT e data URIs.

Conversor Hex para RGB: Guia de códigos de cores para desenvolvedores

Conversor gratuito de Hex para RGB. Aprenda como os códigos de cores hexadecimais funcionam com exemplos em JavaScript, CSS e Python.

Base64 Encoding & Decoding Online Guide: JavaScript, Python, CLI & More

Complete guide to Base64 encoding and decoding online. Learn Base64 in JavaScript (btoa/atob, Buffer), Python, command line (Linux, macOS, OpenSSL, PowerShell), data URIs, JWT, API authentication, URL-safe Base64, performance considerations, and security warnings.