base64.py 1.97 KB
Newer Older
Guido van Rossum's avatar
Guido van Rossum committed
1 2
#! /usr/bin/env python

3 4
"""Conversions to/from base64 transport encoding as per RFC-1521."""

5
# Modified 04-Oct-95 by Jack to use binascii module
6

7
import binascii
8

9 10
__all__ = ["encode","decode","encodestring","decodestring"]

11 12
MAXLINESIZE = 76 # Excluding the CRLF
MAXBINSIZE = (MAXLINESIZE/4)*3
13 14

def encode(input, output):
15 16 17 18 19 20 21 22 23 24
    """Encode a file."""
    while 1:
        s = input.read(MAXBINSIZE)
        if not s: break
        while len(s) < MAXBINSIZE:
            ns = input.read(MAXBINSIZE-len(s))
            if not ns: break
            s = s + ns
        line = binascii.b2a_base64(s)
        output.write(line)
25 26

def decode(input, output):
27 28 29 30 31 32
    """Decode a file."""
    while 1:
        line = input.readline()
        if not line: break
        s = binascii.a2b_base64(line)
        output.write(s)
33 34

def encodestring(s):
35 36 37 38 39 40
    """Encode a string."""
    import StringIO
    f = StringIO.StringIO(s)
    g = StringIO.StringIO()
    encode(f, g)
    return g.getvalue()
41 42

def decodestring(s):
43 44 45 46 47 48
    """Decode a string."""
    import StringIO
    f = StringIO.StringIO(s)
    g = StringIO.StringIO()
    decode(f, g)
    return g.getvalue()
49 50

def test():
51 52 53 54 55 56 57
    """Small test program"""
    import sys, getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'deut')
    except getopt.error, msg:
        sys.stdout = sys.stderr
        print msg
58
        print """usage: %s [-d|-e|-u|-t] [file|-]
59 60
        -d, -u: decode
        -e: encode (default)
61
        -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
62 63 64 65 66 67 68 69 70 71 72
        sys.exit(2)
    func = encode
    for o, a in opts:
        if o == '-e': func = encode
        if o == '-d': func = decode
        if o == '-u': func = decode
        if o == '-t': test1(); return
    if args and args[0] != '-':
        func(open(args[0], 'rb'), sys.stdout)
    else:
        func(sys.stdin, sys.stdout)
73 74

def test1():
75 76 77 78
    s0 = "Aladdin:open sesame"
    s1 = encodestring(s0)
    s2 = decodestring(s1)
    print s0, `s1`, s2
79 80

if __name__ == '__main__':
81
    test()