Update version number and release date.
[python/dscho.git] / Lib / base64.py
blob3158fdcee251925fc954cc271aa54d728f170786
1 #! /usr/bin/env python
3 """Conversions to/from base64 transport encoding as per RFC-1521."""
5 # Modified 04-Oct-95 by Jack to use binascii module
7 import binascii
9 __all__ = ["encode","decode","encodestring","decodestring"]
11 MAXLINESIZE = 76 # Excluding the CRLF
12 MAXBINSIZE = (MAXLINESIZE//4)*3
14 def encode(input, output):
15 """Encode a file."""
16 while 1:
17 s = input.read(MAXBINSIZE)
18 if not s: break
19 while len(s) < MAXBINSIZE:
20 ns = input.read(MAXBINSIZE-len(s))
21 if not ns: break
22 s = s + ns
23 line = binascii.b2a_base64(s)
24 output.write(line)
26 def decode(input, output):
27 """Decode a file."""
28 while 1:
29 line = input.readline()
30 if not line: break
31 s = binascii.a2b_base64(line)
32 output.write(s)
34 def encodestring(s):
35 """Encode a string."""
36 pieces = []
37 for i in range(0, len(s), MAXBINSIZE):
38 chunk = s[i : i + MAXBINSIZE]
39 pieces.append(binascii.b2a_base64(chunk))
40 return "".join(pieces)
42 def decodestring(s):
43 """Decode a string."""
44 return binascii.a2b_base64(s)
46 def test():
47 """Small test program"""
48 import sys, getopt
49 try:
50 opts, args = getopt.getopt(sys.argv[1:], 'deut')
51 except getopt.error, msg:
52 sys.stdout = sys.stderr
53 print msg
54 print """usage: %s [-d|-e|-u|-t] [file|-]
55 -d, -u: decode
56 -e: encode (default)
57 -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
58 sys.exit(2)
59 func = encode
60 for o, a in opts:
61 if o == '-e': func = encode
62 if o == '-d': func = decode
63 if o == '-u': func = decode
64 if o == '-t': test1(); return
65 if args and args[0] != '-':
66 func(open(args[0], 'rb'), sys.stdout)
67 else:
68 func(sys.stdin, sys.stdout)
70 def test1():
71 s0 = "Aladdin:open sesame"
72 s1 = encodestring(s0)
73 s2 = decodestring(s1)
74 print s0, `s1`, s2
76 if __name__ == '__main__':
77 test()