The base64
encoding scheme is used to convert
arbitrary binary data to plain text. To do this, the encoder stores
each group of three binary bytes as a group of four characters from
the following set:
ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789+/
In addition, the =
character is used for padding at
the end of the data stream.
Example 4-18 shows how the encode
and decode
functions work on file objects.
Example 4-18. Using the base64 Module to Encode Files
File: base64-example-1.py import base64 MESSAGE = "life of brian" file = open("out.txt", "w") file.write(MESSAGE) file.close() base64.encode(open("out.txt"), open("out.b64", "w")) base64.decode(open("out.b64"), open("out.txt", "w")) print "original:", repr(MESSAGE) print "encoded message:", repr(open("out.b64").read()) print "decoded message:", repr(open("out.txt").read())original: 'life of brian'
encoded message: 'bGlmZSBvZiBicmlhbg==\012'
decoded message: 'life of brian'
Example 4-19 shows the encodestring
and
decodestring
functions converting between strings. The functions are currently implemented as wrappers on top of
encode
and decode
, using
StringIO
objects for input and output.
Example 4-19. Using the base64 Module to Encode Strings
File: base64-example-2.py import base64 MESSAGE = "life of brian" data = base64.encodestring(MESSAGE) original_data = base64.decodestring(data) print "original:", repr(MESSAGE) print "encoded data:", repr(data) print "decoded data:", repr(original_data)original: 'life of brian'
encoded data: 'bGlmZSBvZiBicmlhbg==\012'
decoded data: 'life of brian'
Example 4-20 shows how to convert a username and a password to an HTTP basic authentication string. (Note that you don’t really have to work for the NSA to be able to decode this format.)
Finally, Example 4-21 shows a small utility that converts a GIF image to a Python script, for use with the Tkinter library.
Example 4-21. Using the base64 Module to Wrap GIF Images for Tkinter
File: base64-example-4.py import base64, sys if not sys.argv[1:]: print "Usage: gif2tk.py giffile >pyfile" sys.exit(1) data = open(sys.argv[1], "rb").read() if data[:4] != "GIF8": print sys.argv[1], "is not a GIF file" sys.exit(1) print '# generated from', sys.argv[1], 'by gif2tk.py' print print 'from Tkinter import PhotoImage' print print 'image = PhotoImage(data="""' print base64.encodestring(data), print '""")'# generated from samples/sample.gif by gif2tk.py
from Tkinter import PhotoImage
image = PhotoImage(data="""
R0lGODlhoAB4APcAAAAAAIAAAACAAICAAAAAgIAAgACAgICAgAQEBIwEBIyMBJRUlISE/LRUBAQE
...
AjmQBFmQBnmQCJmQCrmQDNmQDvmQEBmREnkRAQEAOw==
""")
Get Python Standard Library now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.