0
0
mirror of https://github.com/python/cpython.git synced 2024-11-28 16:45:42 +01:00
cpython/Lib/base64.py

81 lines
1.6 KiB
Python
Raw Normal View History

1997-04-02 07:47:39 +02:00
#! /usr/bin/env python
1995-06-15 01:43:44 +02:00
# Conversions to/from base64 transport encoding as per RFC-MIME (Dec 1991
# version).
# Parameters set by RFX-XXXX.
#
# Modified 04-Oct-95 by Jack to use binascii module
1995-06-15 01:43:44 +02:00
import binascii
1995-06-15 01:43:44 +02:00
MAXLINESIZE = 76 # Excluding the CRLF
MAXBINSIZE = (MAXLINESIZE/4)*3
1995-06-15 01:43:44 +02:00
# Encode a file.
def encode(input, output):
while 1:
s = input.read(MAXBINSIZE)
1995-06-15 01:43:44 +02:00
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)
1995-06-15 01:43:44 +02:00
# Decode a file.
def decode(input, output):
while 1:
line = input.readline()
if not line: break
s = binascii.a2b_base64(line)
output.write(s)
1995-06-15 01:43:44 +02:00
def encodestring(s):
import StringIO
f = StringIO.StringIO(s)
g = StringIO.StringIO()
encode(f, g)
return g.getvalue()
def decodestring(s):
import StringIO
f = StringIO.StringIO(s)
g = StringIO.StringIO()
decode(f, g)
return g.getvalue()
1995-09-18 23:49:24 +02:00
# Small test program
1995-06-15 01:43:44 +02:00
def test():
1995-08-10 21:26:37 +02:00
import sys, getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error, msg:
1995-09-18 23:49:24 +02:00
sys.stdout = sys.stderr
1995-08-10 21:26:37 +02:00
print msg
print """usage: basd64 [-d] [-e] [-u] [-t] [file|-]
-d, -u: decode
-e: encode (default)
-t: decode string 'Aladdin:open sesame'"""
1995-09-18 23:49:24 +02:00
sys.exit(2)
1995-08-10 21:26:37 +02:00
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]), sys.stdout)
1995-06-15 01:43:44 +02:00
else:
1995-08-10 21:26:37 +02:00
func(sys.stdin, sys.stdout)
1995-06-15 01:43:44 +02:00
def test1():
s0 = "Aladdin:open sesame"
s1 = encodestring(s0)
s2 = decodestring(s1)
print s0, `s1`, s2
if __name__ == '__main__':
test()