You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base64.py 2.0KB

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