+++ /dev/null
-#! /usr/bin/env python\r
-\r
-"""RFC 3548: Base16, Base32, Base64 Data Encodings"""\r
-\r
-# Modified 04-Oct-1995 by Jack Jansen to use binascii module\r
-# Modified 30-Dec-2003 by Barry Warsaw to add full RFC 3548 support\r
-\r
-import re\r
-import struct\r
-import binascii\r
-\r
-\r
-__all__ = [\r
- # Legacy interface exports traditional RFC 1521 Base64 encodings\r
- 'encode', 'decode', 'encodestring', 'decodestring',\r
- # Generalized interface for other encodings\r
- 'b64encode', 'b64decode', 'b32encode', 'b32decode',\r
- 'b16encode', 'b16decode',\r
- # Standard Base64 encoding\r
- 'standard_b64encode', 'standard_b64decode',\r
- # Some common Base64 alternatives. As referenced by RFC 3458, see thread\r
- # starting at:\r
- #\r
- # http://zgp.org/pipermail/p2p-hackers/2001-September/000316.html\r
- 'urlsafe_b64encode', 'urlsafe_b64decode',\r
- ]\r
-\r
-_translation = [chr(_x) for _x in range(256)]\r
-EMPTYSTRING = ''\r
-\r
-\r
-def _translate(s, altchars):\r
- translation = _translation[:]\r
- for k, v in altchars.items():\r
- translation[ord(k)] = v\r
- return s.translate(''.join(translation))\r
-\r
-\r
-\f\r
-# Base64 encoding/decoding uses binascii\r
-\r
-def b64encode(s, altchars=None):\r
- """Encode a string using Base64.\r
-\r
- s is the string to encode. Optional altchars must be a string of at least\r
- length 2 (additional characters are ignored) which specifies an\r
- alternative alphabet for the '+' and '/' characters. This allows an\r
- application to e.g. generate url or filesystem safe Base64 strings.\r
-\r
- The encoded string is returned.\r
- """\r
- # Strip off the trailing newline\r
- encoded = binascii.b2a_base64(s)[:-1]\r
- if altchars is not None:\r
- return _translate(encoded, {'+': altchars[0], '/': altchars[1]})\r
- return encoded\r
-\r
-\r
-def b64decode(s, altchars=None):\r
- """Decode a Base64 encoded string.\r
-\r
- s is the string to decode. Optional altchars must be a string of at least\r
- length 2 (additional characters are ignored) which specifies the\r
- alternative alphabet used instead of the '+' and '/' characters.\r
-\r
- The decoded string is returned. A TypeError is raised if s were\r
- incorrectly padded or if there are non-alphabet characters present in the\r
- string.\r
- """\r
- if altchars is not None:\r
- s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})\r
- try:\r
- return binascii.a2b_base64(s)\r
- except binascii.Error, msg:\r
- # Transform this exception for consistency\r
- raise TypeError(msg)\r
-\r
-\r
-def standard_b64encode(s):\r
- """Encode a string using the standard Base64 alphabet.\r
-\r
- s is the string to encode. The encoded string is returned.\r
- """\r
- return b64encode(s)\r
-\r
-def standard_b64decode(s):\r
- """Decode a string encoded with the standard Base64 alphabet.\r
-\r
- s is the string to decode. The decoded string is returned. A TypeError\r
- is raised if the string is incorrectly padded or if there are non-alphabet\r
- characters present in the string.\r
- """\r
- return b64decode(s)\r
-\r
-def urlsafe_b64encode(s):\r
- """Encode a string using a url-safe Base64 alphabet.\r
-\r
- s is the string to encode. The encoded string is returned. The alphabet\r
- uses '-' instead of '+' and '_' instead of '/'.\r
- """\r
- return b64encode(s, '-_')\r
-\r
-def urlsafe_b64decode(s):\r
- """Decode a string encoded with the standard Base64 alphabet.\r
-\r
- s is the string to decode. The decoded string is returned. A TypeError\r
- is raised if the string is incorrectly padded or if there are non-alphabet\r
- characters present in the string.\r
-\r
- The alphabet uses '-' instead of '+' and '_' instead of '/'.\r
- """\r
- return b64decode(s, '-_')\r
-\r
-\r
-\f\r
-# Base32 encoding/decoding must be done in Python\r
-_b32alphabet = {\r
- 0: 'A', 9: 'J', 18: 'S', 27: '3',\r
- 1: 'B', 10: 'K', 19: 'T', 28: '4',\r
- 2: 'C', 11: 'L', 20: 'U', 29: '5',\r
- 3: 'D', 12: 'M', 21: 'V', 30: '6',\r
- 4: 'E', 13: 'N', 22: 'W', 31: '7',\r
- 5: 'F', 14: 'O', 23: 'X',\r
- 6: 'G', 15: 'P', 24: 'Y',\r
- 7: 'H', 16: 'Q', 25: 'Z',\r
- 8: 'I', 17: 'R', 26: '2',\r
- }\r
-\r
-_b32tab = _b32alphabet.items()\r
-_b32tab.sort()\r
-_b32tab = [v for k, v in _b32tab]\r
-_b32rev = dict([(v, long(k)) for k, v in _b32alphabet.items()])\r
-\r
-\r
-def b32encode(s):\r
- """Encode a string using Base32.\r
-\r
- s is the string to encode. The encoded string is returned.\r
- """\r
- parts = []\r
- quanta, leftover = divmod(len(s), 5)\r
- # Pad the last quantum with zero bits if necessary\r
- if leftover:\r
- s += ('\0' * (5 - leftover))\r
- quanta += 1\r
- for i in range(quanta):\r
- # c1 and c2 are 16 bits wide, c3 is 8 bits wide. The intent of this\r
- # code is to process the 40 bits in units of 5 bits. So we take the 1\r
- # leftover bit of c1 and tack it onto c2. Then we take the 2 leftover\r
- # bits of c2 and tack them onto c3. The shifts and masks are intended\r
- # to give us values of exactly 5 bits in width.\r
- c1, c2, c3 = struct.unpack('!HHB', s[i*5:(i+1)*5])\r
- c2 += (c1 & 1) << 16 # 17 bits wide\r
- c3 += (c2 & 3) << 8 # 10 bits wide\r
- parts.extend([_b32tab[c1 >> 11], # bits 1 - 5\r
- _b32tab[(c1 >> 6) & 0x1f], # bits 6 - 10\r
- _b32tab[(c1 >> 1) & 0x1f], # bits 11 - 15\r
- _b32tab[c2 >> 12], # bits 16 - 20 (1 - 5)\r
- _b32tab[(c2 >> 7) & 0x1f], # bits 21 - 25 (6 - 10)\r
- _b32tab[(c2 >> 2) & 0x1f], # bits 26 - 30 (11 - 15)\r
- _b32tab[c3 >> 5], # bits 31 - 35 (1 - 5)\r
- _b32tab[c3 & 0x1f], # bits 36 - 40 (1 - 5)\r
- ])\r
- encoded = EMPTYSTRING.join(parts)\r
- # Adjust for any leftover partial quanta\r
- if leftover == 1:\r
- return encoded[:-6] + '======'\r
- elif leftover == 2:\r
- return encoded[:-4] + '===='\r
- elif leftover == 3:\r
- return encoded[:-3] + '==='\r
- elif leftover == 4:\r
- return encoded[:-1] + '='\r
- return encoded\r
-\r
-\r
-def b32decode(s, casefold=False, map01=None):\r
- """Decode a Base32 encoded string.\r
-\r
- s is the string to decode. Optional casefold is a flag specifying whether\r
- a lowercase alphabet is acceptable as input. For security purposes, the\r
- default is False.\r
-\r
- RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O\r
- (oh), and for optional mapping of the digit 1 (one) to either the letter I\r
- (eye) or letter L (el). The optional argument map01 when not None,\r
- specifies which letter the digit 1 should be mapped to (when map01 is not\r
- None, the digit 0 is always mapped to the letter O). For security\r
- purposes the default is None, so that 0 and 1 are not allowed in the\r
- input.\r
-\r
- The decoded string is returned. A TypeError is raised if s were\r
- incorrectly padded or if there are non-alphabet characters present in the\r
- string.\r
- """\r
- quanta, leftover = divmod(len(s), 8)\r
- if leftover:\r
- raise TypeError('Incorrect padding')\r
- # Handle section 2.4 zero and one mapping. The flag map01 will be either\r
- # False, or the character to map the digit 1 (one) to. It should be\r
- # either L (el) or I (eye).\r
- if map01:\r
- s = _translate(s, {'0': 'O', '1': map01})\r
- if casefold:\r
- s = s.upper()\r
- # Strip off pad characters from the right. We need to count the pad\r
- # characters because this will tell us how many null bytes to remove from\r
- # the end of the decoded string.\r
- padchars = 0\r
- mo = re.search('(?P<pad>[=]*)$', s)\r
- if mo:\r
- padchars = len(mo.group('pad'))\r
- if padchars > 0:\r
- s = s[:-padchars]\r
- # Now decode the full quanta\r
- parts = []\r
- acc = 0\r
- shift = 35\r
- for c in s:\r
- val = _b32rev.get(c)\r
- if val is None:\r
- raise TypeError('Non-base32 digit found')\r
- acc += _b32rev[c] << shift\r
- shift -= 5\r
- if shift < 0:\r
- parts.append(binascii.unhexlify('%010x' % acc))\r
- acc = 0\r
- shift = 35\r
- # Process the last, partial quanta\r
- last = binascii.unhexlify('%010x' % acc)\r
- if padchars == 0:\r
- last = '' # No characters\r
- elif padchars == 1:\r
- last = last[:-1]\r
- elif padchars == 3:\r
- last = last[:-2]\r
- elif padchars == 4:\r
- last = last[:-3]\r
- elif padchars == 6:\r
- last = last[:-4]\r
- else:\r
- raise TypeError('Incorrect padding')\r
- parts.append(last)\r
- return EMPTYSTRING.join(parts)\r
-\r
-\r
-\f\r
-# RFC 3548, Base 16 Alphabet specifies uppercase, but hexlify() returns\r
-# lowercase. The RFC also recommends against accepting input case\r
-# insensitively.\r
-def b16encode(s):\r
- """Encode a string using Base16.\r
-\r
- s is the string to encode. The encoded string is returned.\r
- """\r
- return binascii.hexlify(s).upper()\r
-\r
-\r
-def b16decode(s, casefold=False):\r
- """Decode a Base16 encoded string.\r
-\r
- s is the string to decode. Optional casefold is a flag specifying whether\r
- a lowercase alphabet is acceptable as input. For security purposes, the\r
- default is False.\r
-\r
- The decoded string is returned. A TypeError is raised if s were\r
- incorrectly padded or if there are non-alphabet characters present in the\r
- string.\r
- """\r
- if casefold:\r
- s = s.upper()\r
- if re.search('[^0-9A-F]', s):\r
- raise TypeError('Non-base16 digit found')\r
- return binascii.unhexlify(s)\r
-\r
-\r
-\f\r
-# Legacy interface. This code could be cleaned up since I don't believe\r
-# binascii has any line length limitations. It just doesn't seem worth it\r
-# though.\r
-\r
-MAXLINESIZE = 76 # Excluding the CRLF\r
-MAXBINSIZE = (MAXLINESIZE//4)*3\r
-\r
-def encode(input, output):\r
- """Encode a file."""\r
- while True:\r
- s = input.read(MAXBINSIZE)\r
- if not s:\r
- break\r
- while len(s) < MAXBINSIZE:\r
- ns = input.read(MAXBINSIZE-len(s))\r
- if not ns:\r
- break\r
- s += ns\r
- line = binascii.b2a_base64(s)\r
- output.write(line)\r
-\r
-\r
-def decode(input, output):\r
- """Decode a file."""\r
- while True:\r
- line = input.readline()\r
- if not line:\r
- break\r
- s = binascii.a2b_base64(line)\r
- output.write(s)\r
-\r
-\r
-def encodestring(s):\r
- """Encode a string into multiple lines of base-64 data."""\r
- pieces = []\r
- for i in range(0, len(s), MAXBINSIZE):\r
- chunk = s[i : i + MAXBINSIZE]\r
- pieces.append(binascii.b2a_base64(chunk))\r
- return "".join(pieces)\r
-\r
-\r
-def decodestring(s):\r
- """Decode a string."""\r
- return binascii.a2b_base64(s)\r
-\r
-\r
-\f\r
-# Useable as a script...\r
-def test():\r
- """Small test program"""\r
- import sys, getopt\r
- try:\r
- opts, args = getopt.getopt(sys.argv[1:], 'deut')\r
- except getopt.error, msg:\r
- sys.stdout = sys.stderr\r
- print msg\r
- print """usage: %s [-d|-e|-u|-t] [file|-]\r
- -d, -u: decode\r
- -e: encode (default)\r
- -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]\r
- sys.exit(2)\r
- func = encode\r
- for o, a in opts:\r
- if o == '-e': func = encode\r
- if o == '-d': func = decode\r
- if o == '-u': func = decode\r
- if o == '-t': test1(); return\r
- if args and args[0] != '-':\r
- with open(args[0], 'rb') as f:\r
- func(f, sys.stdout)\r
- else:\r
- func(sys.stdin, sys.stdout)\r
-\r
-\r
-def test1():\r
- s0 = "Aladdin:open sesame"\r
- s1 = encodestring(s0)\r
- s2 = decodestring(s1)\r
- print s0, repr(s1), s2\r
-\r
-\r
-if __name__ == '__main__':\r
- test()\r