1. Home
  2. Blog
  3. Software Development

Software Development

Base64 Encoding Explained: How It Works, With Tested Code

Base64 encoding turns any bytes into text made of 64 safe characters, so binary data can travel through JSON, email, URLs and HTTP headers. See the bit-level steps, padding, URL-safe base64, the 33% size cost and common errors, with Python and JavaScript code we ran.

8 min read
Base64 encoding explained with Python code

Key takeaways

  • Base64 encoding maps every 3 bytes to 4 characters from an alphabet of 64: A to Z, a to z, 0 to 9, plus + and /.
  • = padding fills the last block. “Hello” becomes SGVsbG8=.
  • Output is about 33% larger than input. Our 1,000,000 byte test became 1,333,336 characters.
  • URL-safe base64 swaps + and / for - and _. Base64 is not encryption: anyone can decode it.

You have seen strings like SGVsbG8= in API responses, email source, JWTs and data: URLs. That is base64 encoding, one of the most common formats in software. It lets binary data, such as images, keys or compressed files, travel through systems that only handle text safely.

This guide explains how it works at the bit level, why the output grows, which variant to use where, and the errors you will meet. All Python output comes from Python 3.13.6 and all JavaScript output from Node.js 24.22.1.

What is base64 encoding?

Base64 is a binary-to-text encoding defined in RFC 4648. It represents any sequence of bytes using only 64 printable ASCII characters, plus = for padding. Decoding gives back exactly the original bytes, so nothing is lost. It is an encoding, like UTF-8, not compression and not encryption.

Why base64 exists

Many protocols were designed for text. Email (SMTP) historically carried 7-bit ASCII only. JSON has no byte type. HTTP headers and URLs reserve certain characters. Sending raw bytes through them could corrupt data, because a byte might look like a line ending, a quote or a control character. Base64 sidesteps all of that by using characters that every system treats as plain text.

How base64 works, step by step

Take the three bytes of the word Man. In binary they are:

01001101 01100001 01101110

Base64 regroups those 24 bits into four groups of 6 bits, and each 6-bit number (0 to 63) picks one character from the alphabet:

010011  010110  000101  101110
  19      22      5       46
  T       W       F       u

So Man becomes TWFu. We confirmed both the bit groups and the result in Python. The alphabet runs A to Z (0 to 25), a to z (26 to 51), 0 to 9 (52 to 61), then + (62) and / (63). That is the whole algorithm: 8-bit bytes in, 6-bit characters out.

Padding with =

Input does not always come in multiples of 3 bytes. When the last block is short, base64 pads the output with = so the length is always a multiple of 4:

b'Man'   -> b'TWFu'
b'Ma'    -> b'TWE='
b'M'     -> b'TQ=='
b'Hello' -> b'SGVsbG8='

One leftover byte gives two =, two leftover bytes give one. Some systems, including JWTs, strip the padding. To decode such a string you can add it back with "=" * (-len(s) % 4), as shown in the errors section.

The 33% size cost

Every 3 bytes become 4 characters, so output is four thirds of the input. We measured it:

Input bytes Base64 characters Ratio
3 4 1.333
30 40 1.333
3,000 4,000 1.333
1,000,000 1,333,336 1.333

That overhead matters. Embedding a 300 KB image as a base64 data URI adds about 100 KB, and the browser cannot cache it separately. For large files, upload the raw bytes with multipart form data instead of base64 inside JSON.

URL-safe base64 (base64url)

The standard alphabet uses + and /, which have special meaning in URLs and file paths. The URL-safe variant from RFC 4648 section 5 swaps them for - and _:

b'hi?>'                  standard: b'aGk/Pg=='   url-safe: b'aGk_Pg=='
bytes 250-255 (6 bytes)  standard: b'+vv8/f7/'   url-safe: b'-vv8_f7_'

Use base64url in URLs, cookies, file names and tokens. JWTs use it without padding. We encoded a JWT header and got eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9, the familiar eyJ start of every token. Our JWT guide explains the rest of the token.

Tip: mixing the two variants is a classic bug. A standard decoder treats - and _ as junk, and a URL-safe decoder does the same with + and /. Agree on one variant in your API docs.

Base64 in Python

The standard library base64 module works on bytes, not strings. Encode text to bytes first, usually as UTF-8:

import base64

data = "नमस्ते €".encode("utf-8")
enc = base64.b64encode(data)
print(enc)
# b'4KSo4KSu4KS44KWN4KSk4KWHIOKCrA=='
print(base64.b64decode(enc).decode("utf-8"))
# नमस्ते €

print(base64.urlsafe_b64encode(b"hi?>"))
# b'aGk_Pg=='

Call .decode("ascii") on the encoded bytes when you need a str for JSON. Encoding text this way works for any language, because UTF-8 turns it into bytes first.

Base64 in JavaScript

Browsers and Node.js have btoa() and atob(), but they only handle characters in the Latin-1 range:

btoa("Hello")       // 'SGVsbG8='
atob("SGVsbG8=")    // 'Hello'
btoa("नमस्ते")      // InvalidCharacterError: Invalid character

For Unicode text in Node.js, use Buffer, which also supports base64url directly:

Buffer.from("नमस्ते").toString("base64")   // '4KSo4KSu4KS44KWN4KSk4KWH'
Buffer.from("hi?>").toString("base64url")  // 'aGk_Pg'

Note that Node’s base64url output dropped the padding. In browsers, convert text with TextEncoder to bytes first. Newer engines are adding Uint8Array.prototype.toBase64(), but our Node.js 24.22.1 did not have it yet, so check support before relying on it.

Decode errors and how to fix them

base64.b64decode("SGVsbG8")
# binascii.Error: Incorrect padding

s = "SGVsbG8"
base64.b64decode(s + "=" * (-len(s) % 4))
# b'Hello'

Missing padding is the most common error, usually from a URL-safe source that stripped it. Python also silently ignores characters outside the alphabet by default. Whitespace and newlines are skipped, which helps with wrapped email text, but junk is skipped too. Pass validate=True for strict checking:

base64.b64decode("SGVs*bG8=", validate=True)
# binascii.Error: Only base64 data is allowed

Use strict mode when decoding input from users or other systems, so corrupt data fails loudly instead of decoding into garbage.

Base64 is not encryption

This needs saying plainly. HTTP Basic authentication sends user:password as base64. We encoded a dummy pair:

base64.b64encode(b"demo:not-a-real-password")
# b'ZGVtbzpub3QtYS1yZWFsLXBhc3N3b3Jk'
base64.b64decode(b"ZGVtbzpub3QtYS1yZWFsLXBhc3N3b3Jk")
# b'demo:not-a-real-password'

One function call reverses it, with no key. Base64 hides nothing. Only HTTPS protects Basic auth credentials in transit. Never use base64 to “hide” secrets in config files, URLs or front-end code, and never trust a base64 value just because it looks scrambled.

Where you meet base64

  • Data URIs: data:image/png;base64,... for small inline images and fonts.
  • Email attachments via MIME.
  • JWTs and OAuth tokens, using base64url.
  • HTTP Basic auth headers.
  • APIs that send files or signatures inside JSON.
  • Kubernetes secrets, which store values base64 encoded, again not encrypted.
  • PEM files for TLS certificates and SSH keys, which wrap base64 between header lines.

When you test an API that returns base64, do not just check that the field is present. Decode it in the test and compare the bytes with the expected file or value, and include a case whose length is not a multiple of three so the padding path runs. Those two checks catch most encoding bugs before users see broken images or corrupt downloads.

Base64 vs hex, base32 and base85

Base64 is not the only binary-to-text encoding. Each trades size against readability and character safety. We encoded the same 30 random-looking bytes, and the word “Hi!”, with each one using Python’s base64 module:

Encoding Characters for 30 bytes “Hi!” becomes Typical use
Hex (base16) 60 486921 Hashes, debugging, colour codes
Base32 48 JBUSC=== Case-insensitive codes, such as two-factor secrets
Base64 40 SGkh General purpose, web and email
Base85 38 NNFJ PDF and Git binary patches

Hex doubles the size but is easy to read byte by byte. Base32 avoids lowercase letters and confusing symbols, so people can type it. Base85 is the most compact but uses many punctuation characters that are unsafe in URLs and JSON. Base64 sits in the sweet spot, which is why it became the default.

Base64 on the command line

Most systems include a base64 tool. In Git Bash we ran:

echo -n "Hello" | base64      # SGVsbG8=
echo "SGVsbG8=" | base64 -d   # Hello

Use -n with echo, or the newline gets encoded too and the result changes. On macOS the decode flag is -D on older versions. In PowerShell, use [Convert]::ToBase64String() and [Convert]::FromBase64String() with bytes from [Text.Encoding]::UTF8.GetBytes(). Our Linux commands guide covers more terminal basics.

Final thoughts

Base64 encoding is a simple trick with wide reach: 3 bytes in, 4 safe characters out. Remember that it adds a third to the size, that = pads the last block, that URLs need the URL-safe variant, and that it offers no secrecy. In Python, work in bytes and decode strictly. In JavaScript, avoid btoa for Unicode. With those rules, those mysterious eyJ and SGVs strings stop being mysterious.

FAQ

What is base64 encoding used for?

It carries binary data through text-only channels such as JSON, email, URLs and HTTP headers, for example images in data URIs or tokens in JWTs.

Why does base64 end with an equals sign?

The equals sign is padding. When the input length is not a multiple of three bytes, one or two equals signs fill the final four character block.

How much bigger is base64 than the original?

About 33 percent bigger, because every three bytes become four characters. Our one million byte test produced 1,333,336 characters.

What is the difference between base64 and base64url?

Base64url replaces plus with a hyphen and slash with an underscore, and often drops padding, so the output is safe in URLs and file names.

Is base64 secure for passwords?

No. Base64 is reversible by anyone with no key. Use HTTPS to protect data in transit and proper hashing or encryption for secrets.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
Software Development

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →