Encode Binary for Text Transport
Core idea
Base64 represents arbitrary bytes with ASCII characters; it is reversible encoding, not encryption. base64.b64encode returns bytes and b64decode reverses it. binascii also offers lower-level conversions, including hexadecimal.
import base64encoded = base64.b64encode(b"OK")print(encoded.decode("ascii"))print(base64.b64decode(encoded, validate=True))The encoded ASCII text can be transmitted through text-only interfaces.
Check malformed input
import base64, binasciitry: base64.b64decode("T0s=!", validate=True)except binascii.Error: print("invalid")print(binascii.hexlify(b"OK").decode("ascii"))Strict validation rejects the extra punctuation; hexadecimal is another reversible representation.
Common mistake
Base64 does not conceal secrets or prove integrity. Default b64decode can discard non-alphabet characters; validate=True is useful when your input contract forbids them.
Practice
Encode and decode three different binary payloads; compare their hex and Base64 representations.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Binary transport encodings
Check your understanding of base64 and binascii.
What is printed?
import base64print(base64.b64encode(b"A").decode("ascii"))What is printed?
import binasciiprint(binascii.hexlify(b"AB").decode("ascii"))What does validate=True help reject?
Does Base64 provide confidentiality?