Codificador Base64

Codifique texto para formato Base64 com segurança UTF-8 para APIs e cabeçalhos

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 carry binary data across channels that only reliably support text, such as email (MIME), HTTP headers, and data URIs. The encoding uses the characters A–Z, a–z, 0–9, plus (+), and slash (/), with equals (=) as padding. Every 3 bytes of input produce exactly 4 characters of output, resulting in a predictable 33% size increase.

How the Encoding Algorithm Works

Base64 operates on groups of 3 input bytes (24 bits total). These 24 bits are split into four 6-bit groups, and each 6-bit value maps to one of the 64 characters in the Base64 alphabet. When the input length is not a multiple of 3, the encoder pads the output with one or two equals signs to maintain the 4-character block alignment.

For example, the ASCII string "Hi" contains 2 bytes. The encoder reads 16 bits, pads with zeros to reach 18 bits (three 6-bit groups), and appends a single "=" to signal that one padding byte was added. This deterministic process ensures that any decoder can reconstruct the original binary exactly.

Modern browsers implement Base64 natively via btoa() and atob(), but these functions only handle Latin-1 characters. For UTF-8 text — which includes emojis, CJK characters, and accented letters — you must first encode the string to a UTF-8 byte sequence using TextEncoder before applying Base64 encoding.

Common Use Cases for Base64 Encoding

  • Data URIs: Embed small images, fonts, or SVGs directly in HTML or CSS without additional HTTP requests. The format is data:[mediatype];base64,[data].
  • HTTP Basic Authentication: The Authorization header transmits credentials as Base64(username:password). This is encoding, not encryption — always use HTTPS alongside it.
  • Email attachments (MIME): Binary files are Base64-encoded so they can travel through SMTP servers that only handle 7-bit ASCII text.
  • JSON payloads: APIs that need to include binary blobs (certificates, images, serialized objects) inside JSON use Base64 strings since JSON has no native binary type.
  • Storing binary in text databases: Systems like Redis, DynamoDB attribute values, or CSV exports can safely hold Base64-encoded binary data as plain strings.

UTF-8 Handling and Pitfalls

A common mistake is feeding multi-byte characters directly to btoa(), which throws a DOMException for any character outside the Latin-1 range. The correct approach is to first convert the string to a UTF-8 byte array, then encode those bytes. This tool handles that conversion automatically, so you can safely paste text in any language — including Arabic, Chinese, Japanese, Korean, emojis, and mathematical symbols.

When transmitting Base64-encoded UTF-8 text, document the encoding chain clearly: "UTF-8 text → UTF-8 bytes → Base64 string". The receiver must reverse both steps to reconstruct the original. Omitting the UTF-8 step leads to mojibake (garbled characters) when decoding.

Base64 vs Base64URL

Standard Base64 uses "+" and "/" which are special characters in URLs and filenames. Base64URL (RFC 4648 §5) replaces these with "-" and "_" and omits padding. Use Base64URL when the encoded value will appear in URLs, query parameters, JWT tokens, or filenames. Use standard Base64 when the value stays within HTTP headers, email bodies, or JSON where those characters are safe.

Code Examples

Encoding UTF-8 text to Base64 in JavaScript

// Safe UTF-8 → Base64 encoding (works with any character)
function encodeBase64(text) {
  const encoder = new TextEncoder();
  const bytes = encoder.encode(text);
  const binString = Array.from(bytes, b => String.fromCodePoint(b)).join('');
  return btoa(binString);
}

console.log(encodeBase64('Hello, 世界! 🌍'));

Output:

SGVsbG8sIOS4lueVjCEg8J+MjQ==

Embedding an image as a Data URI

<!-- Small PNG encoded inline — no extra HTTP request -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAA
fFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
  alt="1x1 pixel" width="1" height="1" />

Standards & Specifications

  • RFC 4648 — Defines Base16, Base32, and Base64 encoding alphabets, padding rules, and line-length considerations
  • RFC 2045 §6.8 — Specifies Base64 Content-Transfer-Encoding for MIME email attachments

Perguntas Frequentes

Para que serve a codificação Base64?

A codificação Base64 converte dados binários em formato texto ASCII para transmissão segura via email, HTTP e JSON.

A codificação Base64 criptografa meus dados?

Não! Base64 é um esquema de codificação, não criptografia. Qualquer pessoa pode decodificar dados Base64.

Por que Base64 torna os dados maiores?

A codificação Base64 aumenta o tamanho em aproximadamente 33% porque representa 3 bytes com 4 caracteres ASCII.

Meus dados são enviados para um servidor?

Não, toda a codificação acontece no seu navegador. Seus dados nunca saem do seu dispositivo.