DEV Community

arenasbob2024-cell
arenasbob2024-cell

Posted on • Originally published at viadreams.cc

Base64 Encoding: What It Is and How to Use It

What Is Base64 Encoding?

Base64 is a binary-to-text encoding scheme that converts binary data into a string of ASCII characters. It uses a set of 64 characters (A-Z, a-z, 0-9, +, /) plus = for padding. Base64 is not encryption — it is a reversible encoding used to safely transmit binary data through text-only channels.

How Base64 Works: The 6-Bit Encoding Process

Base64 works by splitting binary data into 6-bit chunks and mapping each chunk to one of 64 printable ASCII characters.

Here is the step-by-step process:

  1. Take the input bytes (8 bits each)
  2. Concatenate all bits into a continuous stream
  3. Split the stream into 6-bit groups
  4. Map each 6-bit value (0-63) to a character from the Base64 alphabet
  5. Pad with = if the input length is not divisible by 3

Encoding Example: "Hi"

ASCII:    H        i
Decimal:  72       105
Binary:   01001000 01101001

Split into 6-bit groups:
010010 000110 1001xx

Pad the last group with zeros:
010010 000110 100100

Base64 index: 18  6  36
Character:     S  G  k

Add padding (input was 2 bytes, need 1 pad):
Result: SGk=
Enter fullscreen mode Exit fullscreen mode

Common Use Cases

1. Data URIs in HTML/CSS

Embed small images directly in HTML without an extra HTTP request:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB
CAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" 
alt="1x1 pixel" />
Enter fullscreen mode Exit fullscreen mode
.icon {
  background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz...);
}
Enter fullscreen mode Exit fullscreen mode

2. JWT Token Payloads

JWT tokens use Base64URL encoding (a URL-safe variant) for the header and payload sections:

// Decode a JWT payload
const token = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U';

const payload = token.split('.')[1];
const decoded = JSON.parse(atob(payload));
console.log(decoded);
// { sub: "1234567890" }
Enter fullscreen mode Exit fullscreen mode

3. HTTP Basic Authentication

Basic Auth encodes credentials as Base64:

const username = 'admin';
const password = 'secret123';
const credentials = btoa(username + ':' + password);

fetch('https://api.example.com/data', {
  headers: {
    'Authorization': 'Basic ' + credentials
  }
});
// Sends: Authorization: Basic YWRtaW46c2VjcmV0MTIz
Enter fullscreen mode Exit fullscreen mode

4. Email Attachments (MIME)

Email protocols like SMTP use Base64 to encode binary attachments so they can travel through text-based email systems.

Base64 in JavaScript

Browser (btoa / atob)

// Encode string to Base64
const encoded = btoa('Hello, World!');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="

// Decode Base64 to string
const decoded = atob('SGVsbG8sIFdvcmxkIQ==');
console.log(decoded); // "Hello, World!"

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

function decodeUnicode(b64) {
  return decodeURIComponent(
    atob(b64).split('').map(
      c => '%' + c.charCodeAt(0).toString(16).padStart(2, '0')
    ).join('')
  );
}

console.log(encodeUnicode('Hello World'));
console.log(decodeUnicode(encodeUnicode('Hello World')));
Enter fullscreen mode Exit fullscreen mode

Node.js (Buffer)

// Encode
const encoded = Buffer.from('Hello, World!').toString('base64');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="

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

// Encode a file to Base64
const fs = require('fs');
const fileBase64 = fs.readFileSync('image.png').toString('base64');
console.log('data:image/png;base64,' + fileBase64);
Enter fullscreen mode Exit fullscreen mode

Base64 in Python

import base64

# Encode a string
text = "Hello, World!"
encoded = base64.b64encode(text.encode('utf-8'))
print(encoded)  # b'SGVsbG8sIFdvcmxkIQ=='
print(encoded.decode('ascii'))  # SGVsbG8sIFdvcmxkIQ==

# Decode
decoded = base64.b64decode(encoded)
print(decoded.decode('utf-8'))  # Hello, World!

# URL-safe Base64 (replaces + with - and / with _)
url_safe = base64.urlsafe_b64encode(b'subjects?id=42')
print(url_safe.decode())  # c3ViamVjdHM_aWQ9NDI=

# Encode a file
with open('document.pdf', 'rb') as f:
    file_b64 = base64.b64encode(f.read()).decode('ascii')
    print(f"Encoded length: {len(file_b64)} characters")
Enter fullscreen mode Exit fullscreen mode

Base64 on the Command Line

# Encode a string
echo -n "Hello, World!" | base64
# SGVsbG8sIFdvcmxkIQ==

# Decode a string
echo "SGVsbG8sIFdvcmxkIQ==" | base64 --decode
# Hello, World!

# Encode a file
base64 < image.png > image.b64

# Decode a file
base64 --decode < image.b64 > image_copy.png

# Encode and copy to clipboard (macOS)
echo -n "secret" | base64 | pbcopy
Enter fullscreen mode Exit fullscreen mode

Base64 Variants

Variant Alphabet Padding Use Case
Standard (RFC 4648) A-Z, a-z, 0-9, +, / = General encoding
URL-safe A-Z, a-z, 0-9, -, _ Optional URLs, filenames, JWT
MIME Standard + line breaks = Email attachments

Important Considerations

  • Size overhead: Base64 increases data size by approximately 33%. A 1 MB file becomes about 1.37 MB when encoded.
  • Not encryption: Base64 provides no security. Anyone can decode it instantly.
  • Performance: For large files, consider streaming encoding rather than loading everything into memory.
  • Line length: MIME Base64 wraps at 76 characters per line. Standard Base64 has no line breaks.

Encode and Decode Instantly

Need to quickly encode or decode Base64 data? Try the DevToolBox Base64 Encoder/Decoder to paste any text or Base64 string and get instant results with file upload support and URL-safe mode.

Top comments (0)