The base64 module
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.
The encode and decode functions work on file objects:
# 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'
The encodestring and decodestring functions convert between strings instead. They’re currently implemented as wrappers on top of encode and decode, using StringIO objects for input and output.
# 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'
Here’s how to convert a user name 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…
# File: base64-example-3.py import base64 def getbasic(user, password): # basic authentication (according to HTTP) return base64.encodestring(user + ":" + password) print getbasic("Aladdin", "open sesame")
'QWxhZGRpbjpvcGVuIHNlc2FtZQ=='
Finally, here’s a small utility that converts a GIF image to a Python script, for use with the Tkinter library:
# 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== """)