How to Base64 encode and decode in Python
Complete guide to Base64 encoding and decoding in Python using the base64 module. Covers bytes vs strings, the encode/decode asymmetry, validate and padding behavior, URL-safe alphabets, streaming files, binascii.Error messages, and Base85 for size.
- python
- programming
- guide
- base64
How to Base64 encode and decode in Python
Python ships a built-in base64 module, so the “encode this” case is a one-liner. What makes Base64 code hard is everything around that one-liner: the bytes/strings boundary, padding, alphabets, and the cryptic binascii.Error messages you get when input is malformed. This guide walks through all of it with the exact exceptions you will hit and the precise fixes for each.
1. The one rule: Base64 operates on bytes
Base64 maps every 3 bytes onto 4 characters from a 64-symbol alphabet. Its input is a byte sequence, never a character sequence. Python enforces this split with two distinct types — str for text, bytes for raw data — and every Base64 bug you will ever write traces back to mixing them up.
So encoding a string has two steps, not one:
import base64
text = "Hello, Base64!"
encoded = base64.b64encode(text.encode('utf-8'))
print(encoded) # b'SGVsbG8sIEJhc2U2NCE='
print(encoded.decode('ascii')) # SGVsbG8sIEJhc2U2NCE=
2. The step beginners skip: str.encode('utf-8')
base64.b64encode does not accept a str. Pass one and you get:
base64.b64encode("Hello") # TypeError
# TypeError: a bytes-like object is required, not 'str'
The fix is .encode('utf-8'), but it matters which codec you pick. 'utf-8' is almost always right because it round-trips any Unicode text losslessly. 'ascii' and 'latin-1' both fail loudly on out-of-range input in Python — encoding 'é' (U+00E9, above ASCII’s 127) raises UnicodeEncodeError with 'ascii', and encoding '€' (U+20AC, above Latin-1’s 255) raises the same with 'latin-1' — so a non-UTF-8 codec choice surfaces as an exception, never as silently wrong Base64. The silent mangling lives on the decode side instead. When you see a decoded result with bytes in the 0xC2–0xC5 range around accented characters — 'é' showing up as é — that is the fingerprint of UTF-8 bytes being decoded as Latin-1/cp1252. Going the other way usually fails loudly: a bare byte like 0xE9 is a valid start of a three-byte UTF-8 sequence, but with no continuation byte in sight, .decode('utf-8') raises UnicodeDecodeError there rather than silently mangling the text.
A related question: why use .encode() instead of a b'...' literal? b'Hello' is fine for pure-ASCII constants, but b'Héllo' is a SyntaxError — bytes literals can only contain ASCII characters directly. The moment your data is dynamic (user input, a variable, anything read from a file), .encode('utf-8') is the only option. Treat b'...' as a way to write test fixtures, and .encode() as the real-world path.
Also note what b64encode gives back: bytes, not str. The asymmetry is deliberate — the output of Base64 is ASCII, which can never fail to decode, so converting the result to text with .decode('ascii') is always safe. Contrast this with the decode direction, where .decode('utf-8') on the decoded bytes can raise UnicodeDecodeError, because Base64 carried arbitrary bytes and there is no guarantee they were ever UTF-8 text in the first place. Same method name, opposite failure modes — that is the single most confusing thing about Python’s Base64 API, and it is worth stopping on until it clicks. If the payload might not be text at all (a PNG file, an encrypted blob), do not call .decode() on it; keep it as bytes and write or hash it directly.
3. Decoding back to a string
The reverse direction is symmetric: b64decode returns bytes, and only your .decode() call turns it into text.
import base64
encoded = "SGVsbG8sIEJhc2U2NCE="
text = base64.b64decode(encoded).decode('utf-8')
print(text) # Hello, Base64!
The signature is b64decode(s, altchars=None, validate=False), and that default validate=False hides surprising behavior. With validation off, every character outside the Base64 alphabet is silently discarded before decoding — newline-wrapped email attachments decode fine, and same-length corruptions pass through as garbage: swap one character in a valid string, SGVsbG8gQmFzZTY0IQ== → SGV8bG8gQmFzZTY0IQ==, and it silently decodes to wrong bytes. The leniency has a hard floor, though — any change that alters the data-character count raises binascii.Error: Incorrect padding even with validate=False, so a truncated string like "SG#Vsb!G8" (7 data characters after the invalid ones are dropped) cannot be silently rescued. Flip validate=True and out-of-alphabet characters raise binascii.Error instead. Use validate=True in any interop scenario where you want garbage rejected rather than ignored; use the default only for tolerant input like MIME bodies.
4. Padding: the one-liner repair
Base64 output length is always a multiple of 4, padded with =. The three padding cases encode how many bytes were in the final group: no padding for a multiple of 3, = for one leftover byte, == for two. This is also why a valid Base64 string can never have 1, 5, or 9 non-padding characters mod 4 — information-theoretically, one leftover character cannot encode a full byte.
URL-safe and JWT systems strip the = because padding is redundant and = is reserved in URLs. Python’s decoder still requires it, so the repair is a one-liner:
# Add padding back if needed
def b64decode_flexible(s):
padding = 4 - len(s) % 4
if padding != 4:
s += '=' * padding
return base64.b64decode(s, validate=True)
print(b64decode_flexible("SGVsbG8sIEJhc2U2NCE").decode('utf-8'))
# Hello, Base64!
One subtlety: stripping padding is lossless, but truncating output (chopping real characters off the end) is not — Base64 groups of 4 encode 3 bytes, so a truncated string cannot be repaired, only replaced.
5. Reading binascii.Error messages
The low-level decoder raises binascii.Error, and its messages are terse but literal once you know the format rules:
| Error | What it actually means |
|---|---|
binascii.Error: Invalid base64-encoded string: number of data characters (X) cannot be 1 more than a multiple of 4 |
Length mod 4 is 1 after padding — one stray character, almost always truncation or a copy/paste cut |
binascii.Error: Incorrect padding |
Length is 2 or 3 mod 4 — missing = characters, the classic stripped-padding case |
binascii.Error: Discontinuous padding not allowed |
A = appears in the middle of the string (Python 3.11+); some writers put padding per line of MIME output and validators reject it |
binascii.Error: Only base64 data is allowed |
A character outside the Base64 alphabet hit validate=True. Version nuance: Python 3.10 raises Non-base64 digit found from the module’s own check, but since 3.11 b64decode is a thin wrapper over binascii.a2b_base64(s, strict_mode=validate) and that message lives in binascii. The encoder that produced this did not use the standard alphabet — try URL-safe, or pass altchars |
UnicodeDecodeError on the decoded bytes |
Decoding succeeded; the bytes just are not UTF-8. This is your codec problem, not a Base64 problem |
The last row is the one worth internalizing: a UnicodeDecodeError after b64decode is never a bug in the Base64 step. The Base64 layer did its job perfectly — it delivered some byte sequence. The failure is your assumption that those bytes were text.
6. When you already have bytes
If your input comes from a file read in 'rb' mode, a network socket, an io.BytesIO buffer, or a hash digest (hashlib.md5(...).digest()), skip .encode() entirely — the data is already bytes:
import base64
raw = b'\x00\x01\x02\xff\xfe'
encoded = base64.b64encode(raw)
print(base64.b64decode(encoded) == raw) # True
This is also where you notice b64encode output being bytes matters practically: if you are building a JSON payload or sticking the value into urllib, call .decode('ascii') on it first, because JSON serializers refuse bytes.
7. URL-safe Base64 and JWTs
The standard alphabet uses + and /. Both are problematic: + inside a URL query string means space, and / breaks route segments and restrictions in filenames. The URL-safe variant swaps in - and _ — Python’s urlsafe_b64encode performs the same alphabet swap via a translation table under the hood (the same effect as passing altchars).
import base64
text = "https://example.com/path?q=1"
encoded = base64.urlsafe_b64encode(text.encode('utf-8')).rstrip(b'=')
print(encoded.decode('ascii'))
We strip the = here because that is exactly what a JWT does. A Python JWT (any pyjwt-style setup, or the manual path below) is three base64url segments — header, payload, signature — each padded-stripped, joined by dots. JWT libraries handle this for you; manually, here is the exact translation:
def b64url_encode(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b'=').decode('ascii')
def b64url_decode(segment: str) -> bytes:
return base64.urlsafe_b64decode(segment + '=' * (-len(segment) % 4))
Note -len(segment) % 4 — Python’s % on negative numbers returns a non-negative result, so this expression yields exactly 2, 1, or 0 padding characters. It is shorter and safer than the 4 - len % 4 arithmetic, which needs the != 4 guard. For a deeper explanation of why two alphabets exist and when to use each, see URL-safe Base64.
8. Files: chunk sizes are not a detail
The naive file recipes all have the same bug — every b64encode(chunk) call emits its own padding, and unless each chunk is a multiple of 3 bytes, you get = sprinkled through the middle of the output that other decoders will reject. 64 KB is not a multiple of 3; 65,532 bytes is. Either pick chunk sizes that are multiples of 3:
import base64
with open('large.bin', 'rb') as f_in, open('large.b64', 'wb') as f_out:
while chunk := f_in.read(3 * 32768): # multiple-of-3 chunks only
f_out.write(base64.b64encode(chunk))
or read the whole file and let Python do it in one shot (b64encode(f.read())), which is fine up to a few hundred MB — beyond that, b64encode needs the input bytes (1.0×) and the output bytes (~1.33× the input) in memory at once, so RAM per call becomes the practical ceiling. For decoding text files that contain Base64 wrapped at 76 characters (MIME standard), use base64.decodebytes — the strict sibling: it uses the low-level decoder’s tolerant whitespace handling and rejects str outright (TypeError), while plain b64decode is the deliberately lenient twin — it even accepts an ASCII str (raising ValueError only for non-ASCII text), which is why the decode examples earlier in this guide work without .encode():
import base64
with open('wrapped.b64', 'rb') as f:
decoded = base64.decodebytes(f.read())
The difference from b64decode: both skip non-alphabet characters when validate=False, but decodebytes never accepts str, making it the stricter, bytes-typed choice for file work, and it explicitly documents line-break tolerance. For files destined for HTML or CSS — images included — turning a whole file into Base64 is the subject of the dedicated file-to-Base64 tool — the same client-side mechanics, packaged for whole-file input.
9. Blowing past Base64: Base85
Base64 spends 4 characters per 3 bytes — 33% overhead. If size matters (embedding data in JSON, log lines, config files), base64.b85encode uses 85 printable symbols to pack 4 bytes into 5 characters, cutting overhead to 25% — roughly 6% smaller output than Base64, and the family has proven variants: Ascii85 (PostScript/PDF), Git’s base85 (binary diffs), and z85 (ZeroMQ). The tradeoff: the Base85 alphabet includes characters like $ and ; that are not URL-safe, so its use is really for where you have full control over the channel, not for cookies or query parameters.
import base64
import os
key = os.urandom(32)
print(len(base64.b64encode(key))) # 44
print(len(base64.b85encode(key))) # 40
For a quick answer to “how big will this be at ratio X”, the Base64 size calculator does the arithmetic without writing code.
10. Base64 is not encryption
This is worth repeating in any language’s guide: Base64 is an encoding, not a cipher — it has no key, and anyone can reverse it. There is a full write-up in Is Base64 encryption?; the Python-specific mistake is treating b64encode as “obfuscation” for storing passwords or API keys:
# WRONG — anyone with 5 seconds reverses this
secret = base64.b64encode(b"my-password").decode('ascii')
# RIGHT — encrypt, then optionally Base64-encode ciphertext for a text channel
# from cryptography.fernet import Fernet
# cipher = Fernet(Fernet.generate_key())
# safe_for_text = cipher.encrypt(b"my-password").decode('ascii')
Note that Fernet already base64urls its own output, so a second layer of encoding is usually redundant there — the pattern is really “encrypt, then whatever your transport demands.”
Try it in the browser
If you want to sanity-check an input/output pair or compare alphabets without firing up an interpreter:
- Base64 encoder — encode text or files, with charset control
- Base64 decoder — decode and inspect raw bytes, with padding hints
- Base64 to hex — cross-check Base64 payloads against a hex dump
Everything runs client-side in your browser; nothing is uploaded.
Full working example
import base64
def encode_text(text: str) -> str:
return base64.b64encode(text.encode('utf-8')).decode('ascii')
def decode_text(encoded: str) -> str:
encoded += '=' * (-len(encoded) % 4)
return base64.b64decode(encoded, validate=True).decode('utf-8')
original = "Python + Base64 = 🚀"
assert decode_text(encode_text(original)) == original
Try it yourself — right now
Both tools run 100% in your browser. Nothing you type or drop is ever uploaded.
Related posts
Related posts
October 28, 2026
Character Sets Explained: How Encoding Detection Works and Why It Matters for Base64
Base64 moves bytes, but characters become bytes through a character set. This guide explains ASCII, Unicode, UTF-8, legacy code pages, CJK and EBCDIC, how auto-detection works, and why picking the wrong charset turns readable text into mojibake.
October 26, 2026
Base64 data URLs: how to embed images in HTML, CSS, JSON and email
A complete, practical guide to data::URLs — when embedding an image inline with Base64 beats a regular request, the bandwidth trade-off nobody sells you, MIME types done right, CSP and email gotchas, and copy-paste syntax for HTML, CSS, SVG, JSON and Python.
October 20, 2026
How to Base64 encode and decode in JavaScript: btoa, atob, Buffer, and Data URLs
A complete, copy-paste-tested guide to Base64 in JavaScript: the btoa/atob basics, the Unicode trap that breaks naive code, TextEncoder done right, Node Buffer equivalents, and Data URL patterns for files.