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:


In addition, the = character is used for padding at the end of the data stream.

The encode and decode functions work on file objects:

Example: Using the base64 module to encode files
# File:

import base64

MESSAGE = "life of brian"

file = open("out.txt", "w")

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.

Example: Using the base64 module to encode strings
# File:

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…

Example: Using the base64 module for basic authentication
# File:

import base64

def getbasic(user, password):
    # basic authentication (according to HTTP)
    return base64.encodestring(user + ":" + password)    

print getbasic("Aladdin", "open sesame")


Finally, here’s a small utility that converts a GIF image to a Python script, for use with the Tkinter library:

Example: Using the base64 module to wrap GIF images for Tkinter
# File:

import base64, sys

if not sys.argv[1:]:
    print "Usage: giffile >pyfile"

data = open(sys.argv[1], "rb").read()

if data[:4] != "GIF8":
    print sys.argv[1], "is not a GIF file"

print '# generated from', sys.argv[1], 'by'
print 'from Tkinter import PhotoImage' 
print 'image = PhotoImage(data="""'
print base64.encodestring(data),
print '""")'

# generated from samples/sample.gif by

from Tkinter import PhotoImage

image = PhotoImage(data="""

A Django site. rendered by a django application. hosted by webfaction.