base64

Bytes in, ASCII bytes out — and back. Every encoder takes bytes and returns bytes, so text needs .encode() before and .decode() after. Bad input raises binascii.Error, a ValueError subclass.

Data formatsPython 3.0+Live demo
Import
import base64
from base64 import b64encode, b64decode
Public API
b64encode/b64decode, standard_ and urlsafe_ variants, b32*, b32hex*, b16*, a85*, b85*, z85*, encodebytes/decodebytes, encode/decode
Specs
RFC 4648 (Base64, Base32, Base16), RFC 2045 (MIME lines), Ascii85, Git-style Base85, ZeroMQ Z85
Errors
binascii.Error (a ValueError) for bad Base64/32/16; plain ValueError for the 85 family
Speed
Base64 and Base16 run in C (binascii); Base32 and the 85 codecs are pure Python
CLI
python -m base64 file (encode) · python -m base64 -d file (decode)

Demo

Live evaluation
The everyday recipe: str → bytes (encode) → Base64 bytes → and back to the original str.
Try:
Inputs
textstrany text
Code
import base64
encoded = base64.b64encode('hello world'.encode())
(encoded, base64.b64decode(encoded).decode())
Result
(b'aGVsbG8gd29ybGQ=', 'hello world')

Base64 writes every 3 input bytes as 4 characters and pads the last group with = — so "a" (1 byte) becomes YQ== and the output is always a multiple of 4 long. Base32 uses 8 characters per 5 bytes, hex 2 per byte, the 85 codecs 5 per 4 bytes (the most compact). "???>>>" shows the only difference between standard and URL-safe Base64: + and / become - and _.

Members

Functions9
LIVE
base64.a85encode / b85encode / z85encode
a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)
The Base85 family — Ascii85 (PDF, PostScript), Base85 (Git binary patches) and Z85 (ZeroMQ): 5 characters per 4 bytes.
LIVE
base64.b16encode / b16decode
b16decode(s, casefold=False)
Base16 — uppercase hexadecimal: two characters per byte, strict about case and stray characters.
LIVE
base64.b32encode / b32decode
b32decode(s, casefold=False, map01=None)
Base32 (A–Z and 2–7) and Base32hex (0–9 and A–V): 8 characters per 5 bytes, case-insensitive on request.
LIVE
base64.b64decode
b64decode(s, altchars=None, validate=False)
Decode Base64 text (str or bytes) back into the original bytes; raises binascii.Error on bad padding.
LIVE
base64.b64encode
b64encode(s, altchars=None)
Encode bytes as Base64 and return the result as ASCII bytes (no newlines, = padding included).
LIVE
base64.encode / decode
encode(input, output)
Stream Base64 between binary file objects: encode writes 76-character lines, decode reads a line at a time.
LIVE
base64.encodebytes / decodebytes
encodebytes(s)
MIME-style Base64: lines of at most 76 characters, each ending in a newline — and the matching decoder.
LIVE
base64.standard_b64encode / standard_b64decode
standard_b64encode(s)
Base64 with the standard RFC 4648 alphabet (+ and /) — b64encode and b64decode without the optional arguments.
LIVE
base64.urlsafe_b64encode / urlsafe_b64decode
urlsafe_b64encode(s)
Base64 with - and _ instead of + and /, safe in URLs, file names and JWTs.

Common patterns

Encode a string to Base64 text
Encode the text to bytes, Base64 it, decode the ASCII result back to str.
import base64
token = base64.b64encode(text.encode('utf-8')).decode('ascii')
Decode Base64 text back to a string
b64decode accepts str; the result is bytes — decode with the charset the sender used.
import base64
text = base64.b64decode(token).decode('utf-8')
Embed a file as a data: URI
Read the file in binary mode; the Base64 text goes after the comma.
import base64
with open('logo.png', 'rb') as f:
    uri = 'data:image/png;base64,' + base64.b64encode(f.read()).decode('ascii')
Basic auth header
HTTP Basic credentials are Base64 of "user:password" — encoding, not encryption.
import base64
creds = base64.b64encode(f'{user}:{password}'.encode()).decode()
headers = {'Authorization': f'Basic {creds}'}
Encode or decode from the shell
The module runs as a script; output uses 76-character MIME lines.
# shell:
# python -m base64 photo.jpg > photo.b64
# python -m base64 -d photo.b64 > photo.jpg

Examples

1. str → Base64 str
import base64 base64.b64encode('hello world'.encode()).decode('ascii')
Returns
'aGVsbG8gd29ybGQ='
2. Base64 str → str
import base64 base64.b64decode('aGVsbG8gd29ybGQ=').decode()
Returns
'hello world'
3. Output is bytes
import base64 base64.b64encode(b'hi')
Returns
b'aGk='
4. Encoders refuse str
import base64 base64.b64encode('hi')
Returns
TypeError: a bytes-like object is required, not 'str'
5. Missing padding
import base64 base64.b64decode('aGVsbG8')
Returns
binascii.Error: Incorrect padding
6. URL-safe alphabet
import base64 base64.urlsafe_b64encode(b'\xfb\xff\xbf')
Returns
b'-_-_'
7. Same bytes, other bases
import base64 [base64.b16encode(b'hi'), base64.b32encode(b'hi'), base64.b85encode(b'hi')]
Returns
[b'6869', b'NBUQ====', b'XlV']

Pitfalls

1. Showing the bytes repr instead of the text
str() of bytes gives the repr, b'...' included — which ends up in JSON, headers and HTML. Decode the ASCII bytes instead.
str(bytes)
import base64
f'token={base64.b64encode(b"hi")}'
"token=b'aGk='"
.decode('ascii')
import base64
f'token={base64.b64encode(b"hi").decode("ascii")}'
'token=aGk='
2. Thinking Base64 is encryption
Anyone can decode it — there is no key. Use it to carry bytes through text channels, never to hide secrets.
"hidden" password
import base64
base64.b64decode('c2VjcmV0')
b'secret'
hash passwords instead
import hashlib
hashlib.sha256(b'secret').hexdigest()[:16]
'2bb80d537b1da3e3'

When to use

Use it
  • Putting binary data (images, keys, hashes) into JSON, XML, URLs, email or HTTP headers
  • data: URIs, HTTP Basic auth, JWT segments (URL-safe, unpadded)
  • Case-insensitive or human-typed codes → Base32
Reach for something else
  • Hiding or protecting data — Base64 is reversible by anyone → hashlib / secrets / a crypto library
  • Hex dumps of bytes → bytes.hex() and bytes.fromhex() are simpler
  • Storing binary data where bytes are allowed — Base64 adds a third to the size

Notes

CPython impl
Lib/base64.py — Base64 and Base16 are thin wrappers over the C functions binascii.b2a_base64 / a2b_base64 / hexlify; Base32 and Base85 are implemented in Python
Size
Base64 output is 4 × ceil(n / 3) characters: one third bigger than the input, plus padding
Errors
binascii.Error subclasses ValueError, so except ValueError catches every decoding failure in the module

FAQ

base64.b64encode(text.encode('utf-8')).decode('ascii'). b64encode only accepts bytes, so the string is encoded first; it returns bytes, so the result is decoded to get a str.