base64.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. #! /usr/bin/env python3
  2. """Base16, Base32, Base64 (RFC 3548), Base85 and Ascii85 data encodings"""
  3. # Modified 04-Oct-1995 by Jack Jansen to use binascii module
  4. # Modified 30-Dec-2003 by Barry Warsaw to add full RFC 3548 support
  5. # Modified 22-May-2007 by Guido van Rossum to use bytes everywhere
  6. import re
  7. import struct
  8. import binascii
  9. __all__ = [
  10. # Legacy interface exports traditional RFC 2045 Base64 encodings
  11. 'encode', 'decode', 'encodebytes', 'decodebytes',
  12. # Generalized interface for other encodings
  13. 'b64encode', 'b64decode', 'b32encode', 'b32decode',
  14. 'b16encode', 'b16decode',
  15. # Base85 and Ascii85 encodings
  16. 'b85encode', 'b85decode', 'a85encode', 'a85decode',
  17. # Standard Base64 encoding
  18. 'standard_b64encode', 'standard_b64decode',
  19. # Some common Base64 alternatives. As referenced by RFC 3458, see thread
  20. # starting at:
  21. #
  22. # http://zgp.org/pipermail/p2p-hackers/2001-September/000316.html
  23. 'urlsafe_b64encode', 'urlsafe_b64decode',
  24. ]
  25. bytes_types = (bytes, bytearray) # Types acceptable as binary data
  26. def _bytes_from_decode_data(s):
  27. if isinstance(s, str):
  28. try:
  29. return s.encode('ascii')
  30. except UnicodeEncodeError:
  31. raise ValueError('string argument should contain only ASCII characters')
  32. if isinstance(s, bytes_types):
  33. return s
  34. try:
  35. return memoryview(s).tobytes()
  36. except TypeError:
  37. raise TypeError("argument should be a bytes-like object or ASCII "
  38. "string, not %r" % s.__class__.__name__) from None
  39. # Base64 encoding/decoding uses binascii
  40. def b64encode(s, altchars=None):
  41. """Encode the bytes-like object s using Base64 and return a bytes object.
  42. Optional altchars should be a byte string of length 2 which specifies an
  43. alternative alphabet for the '+' and '/' characters. This allows an
  44. application to e.g. generate url or filesystem safe Base64 strings.
  45. """
  46. encoded = binascii.b2a_base64(s, newline=False)
  47. if altchars is not None:
  48. assert len(altchars) == 2, repr(altchars)
  49. return encoded.translate(bytes.maketrans(b'+/', altchars))
  50. return encoded
  51. def b64decode(s, altchars=None, validate=False):
  52. """Decode the Base64 encoded bytes-like object or ASCII string s.
  53. Optional altchars must be a bytes-like object or ASCII string of length 2
  54. which specifies the alternative alphabet used instead of the '+' and '/'
  55. characters.
  56. The result is returned as a bytes object. A binascii.Error is raised if
  57. s is incorrectly padded.
  58. If validate is False (the default), characters that are neither in the
  59. normal base-64 alphabet nor the alternative alphabet are discarded prior
  60. to the padding check. If validate is True, these non-alphabet characters
  61. in the input result in a binascii.Error.
  62. """
  63. s = _bytes_from_decode_data(s)
  64. if altchars is not None:
  65. altchars = _bytes_from_decode_data(altchars)
  66. assert len(altchars) == 2, repr(altchars)
  67. s = s.translate(bytes.maketrans(altchars, b'+/'))
  68. if validate and not re.fullmatch(b'[A-Za-z0-9+/]*={0,2}', s):
  69. raise binascii.Error('Non-base64 digit found')
  70. return binascii.a2b_base64(s)
  71. def standard_b64encode(s):
  72. """Encode bytes-like object s using the standard Base64 alphabet.
  73. The result is returned as a bytes object.
  74. """
  75. return b64encode(s)
  76. def standard_b64decode(s):
  77. """Decode bytes encoded with the standard Base64 alphabet.
  78. Argument s is a bytes-like object or ASCII string to decode. The result
  79. is returned as a bytes object. A binascii.Error is raised if the input
  80. is incorrectly padded. Characters that are not in the standard alphabet
  81. are discarded prior to the padding check.
  82. """
  83. return b64decode(s)
  84. _urlsafe_encode_translation = bytes.maketrans(b'+/', b'-_')
  85. _urlsafe_decode_translation = bytes.maketrans(b'-_', b'+/')
  86. def urlsafe_b64encode(s):
  87. """Encode bytes using the URL- and filesystem-safe Base64 alphabet.
  88. Argument s is a bytes-like object to encode. The result is returned as a
  89. bytes object. The alphabet uses '-' instead of '+' and '_' instead of
  90. '/'.
  91. """
  92. return b64encode(s).translate(_urlsafe_encode_translation)
  93. def urlsafe_b64decode(s):
  94. """Decode bytes using the URL- and filesystem-safe Base64 alphabet.
  95. Argument s is a bytes-like object or ASCII string to decode. The result
  96. is returned as a bytes object. A binascii.Error is raised if the input
  97. is incorrectly padded. Characters that are not in the URL-safe base-64
  98. alphabet, and are not a plus '+' or slash '/', are discarded prior to the
  99. padding check.
  100. The alphabet uses '-' instead of '+' and '_' instead of '/'.
  101. """
  102. s = _bytes_from_decode_data(s)
  103. s = s.translate(_urlsafe_decode_translation)
  104. return b64decode(s)
  105. # Base32 encoding/decoding must be done in Python
  106. _b32alphabet = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
  107. _b32tab2 = None
  108. _b32rev = None
  109. def b32encode(s):
  110. """Encode the bytes-like object s using Base32 and return a bytes object.
  111. """
  112. global _b32tab2
  113. # Delay the initialization of the table to not waste memory
  114. # if the function is never called
  115. if _b32tab2 is None:
  116. b32tab = [bytes((i,)) for i in _b32alphabet]
  117. _b32tab2 = [a + b for a in b32tab for b in b32tab]
  118. b32tab = None
  119. if not isinstance(s, bytes_types):
  120. s = memoryview(s).tobytes()
  121. leftover = len(s) % 5
  122. # Pad the last quantum with zero bits if necessary
  123. if leftover:
  124. s = s + b'\0' * (5 - leftover) # Don't use += !
  125. encoded = bytearray()
  126. from_bytes = int.from_bytes
  127. b32tab2 = _b32tab2
  128. for i in range(0, len(s), 5):
  129. c = from_bytes(s[i: i + 5], 'big')
  130. encoded += (b32tab2[c >> 30] + # bits 1 - 10
  131. b32tab2[(c >> 20) & 0x3ff] + # bits 11 - 20
  132. b32tab2[(c >> 10) & 0x3ff] + # bits 21 - 30
  133. b32tab2[c & 0x3ff] # bits 31 - 40
  134. )
  135. # Adjust for any leftover partial quanta
  136. if leftover == 1:
  137. encoded[-6:] = b'======'
  138. elif leftover == 2:
  139. encoded[-4:] = b'===='
  140. elif leftover == 3:
  141. encoded[-3:] = b'==='
  142. elif leftover == 4:
  143. encoded[-1:] = b'='
  144. return bytes(encoded)
  145. def b32decode(s, casefold=False, map01=None):
  146. """Decode the Base32 encoded bytes-like object or ASCII string s.
  147. Optional casefold is a flag specifying whether a lowercase alphabet is
  148. acceptable as input. For security purposes, the default is False.
  149. RFC 3548 allows for optional mapping of the digit 0 (zero) to the
  150. letter O (oh), and for optional mapping of the digit 1 (one) to
  151. either the letter I (eye) or letter L (el). The optional argument
  152. map01 when not None, specifies which letter the digit 1 should be
  153. mapped to (when map01 is not None, the digit 0 is always mapped to
  154. the letter O). For security purposes the default is None, so that
  155. 0 and 1 are not allowed in the input.
  156. The result is returned as a bytes object. A binascii.Error is raised if
  157. the input is incorrectly padded or if there are non-alphabet
  158. characters present in the input.
  159. """
  160. global _b32rev
  161. # Delay the initialization of the table to not waste memory
  162. # if the function is never called
  163. if _b32rev is None:
  164. _b32rev = {v: k for k, v in enumerate(_b32alphabet)}
  165. s = _bytes_from_decode_data(s)
  166. if len(s) % 8:
  167. raise binascii.Error('Incorrect padding')
  168. # Handle section 2.4 zero and one mapping. The flag map01 will be either
  169. # False, or the character to map the digit 1 (one) to. It should be
  170. # either L (el) or I (eye).
  171. if map01 is not None:
  172. map01 = _bytes_from_decode_data(map01)
  173. assert len(map01) == 1, repr(map01)
  174. s = s.translate(bytes.maketrans(b'01', b'O' + map01))
  175. if casefold:
  176. s = s.upper()
  177. # Strip off pad characters from the right. We need to count the pad
  178. # characters because this will tell us how many null bytes to remove from
  179. # the end of the decoded string.
  180. l = len(s)
  181. s = s.rstrip(b'=')
  182. padchars = l - len(s)
  183. # Now decode the full quanta
  184. decoded = bytearray()
  185. b32rev = _b32rev
  186. for i in range(0, len(s), 8):
  187. quanta = s[i: i + 8]
  188. acc = 0
  189. try:
  190. for c in quanta:
  191. acc = (acc << 5) + b32rev[c]
  192. except KeyError:
  193. raise binascii.Error('Non-base32 digit found') from None
  194. decoded += acc.to_bytes(5, 'big')
  195. # Process the last, partial quanta
  196. if l % 8 or padchars not in {0, 1, 3, 4, 6}:
  197. raise binascii.Error('Incorrect padding')
  198. if padchars and decoded:
  199. acc <<= 5 * padchars
  200. last = acc.to_bytes(5, 'big')
  201. leftover = (43 - 5 * padchars) // 8 # 1: 4, 3: 3, 4: 2, 6: 1
  202. decoded[-5:] = last[:leftover]
  203. return bytes(decoded)
  204. # RFC 3548, Base 16 Alphabet specifies uppercase, but hexlify() returns
  205. # lowercase. The RFC also recommends against accepting input case
  206. # insensitively.
  207. def b16encode(s):
  208. """Encode the bytes-like object s using Base16 and return a bytes object.
  209. """
  210. return binascii.hexlify(s).upper()
  211. def b16decode(s, casefold=False):
  212. """Decode the Base16 encoded bytes-like object or ASCII string s.
  213. Optional casefold is a flag specifying whether a lowercase alphabet is
  214. acceptable as input. For security purposes, the default is False.
  215. The result is returned as a bytes object. A binascii.Error is raised if
  216. s is incorrectly padded or if there are non-alphabet characters present
  217. in the input.
  218. """
  219. s = _bytes_from_decode_data(s)
  220. if casefold:
  221. s = s.upper()
  222. if re.search(b'[^0-9A-F]', s):
  223. raise binascii.Error('Non-base16 digit found')
  224. return binascii.unhexlify(s)
  225. #
  226. # Ascii85 encoding/decoding
  227. #
  228. _a85chars = None
  229. _a85chars2 = None
  230. _A85START = b"<~"
  231. _A85END = b"~>"
  232. def _85encode(b, chars, chars2, pad=False, foldnuls=False, foldspaces=False):
  233. # Helper function for a85encode and b85encode
  234. if not isinstance(b, bytes_types):
  235. b = memoryview(b).tobytes()
  236. padding = (-len(b)) % 4
  237. if padding:
  238. b = b + b'\0' * padding
  239. words = struct.Struct('!%dI' % (len(b) // 4)).unpack(b)
  240. chunks = [b'z' if foldnuls and not word else
  241. b'y' if foldspaces and word == 0x20202020 else
  242. (chars2[word // 614125] +
  243. chars2[word // 85 % 7225] +
  244. chars[word % 85])
  245. for word in words]
  246. if padding and not pad:
  247. if chunks[-1] == b'z':
  248. chunks[-1] = chars[0] * 5
  249. chunks[-1] = chunks[-1][:-padding]
  250. return b''.join(chunks)
  251. def a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False):
  252. """Encode bytes-like object b using Ascii85 and return a bytes object.
  253. foldspaces is an optional flag that uses the special short sequence 'y'
  254. instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This
  255. feature is not supported by the "standard" Adobe encoding.
  256. wrapcol controls whether the output should have newline (b'\\n') characters
  257. added to it. If this is non-zero, each output line will be at most this
  258. many characters long.
  259. pad controls whether the input is padded to a multiple of 4 before
  260. encoding. Note that the btoa implementation always pads.
  261. adobe controls whether the encoded byte sequence is framed with <~ and ~>,
  262. which is used by the Adobe implementation.
  263. """
  264. global _a85chars, _a85chars2
  265. # Delay the initialization of tables to not waste memory
  266. # if the function is never called
  267. if _a85chars2 is None:
  268. _a85chars = [bytes((i,)) for i in range(33, 118)]
  269. _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]
  270. result = _85encode(b, _a85chars, _a85chars2, pad, True, foldspaces)
  271. if adobe:
  272. result = _A85START + result
  273. if wrapcol:
  274. wrapcol = max(2 if adobe else 1, wrapcol)
  275. chunks = [result[i: i + wrapcol]
  276. for i in range(0, len(result), wrapcol)]
  277. if adobe:
  278. if len(chunks[-1]) + 2 > wrapcol:
  279. chunks.append(b'')
  280. result = b'\n'.join(chunks)
  281. if adobe:
  282. result += _A85END
  283. return result
  284. def a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v'):
  285. """Decode the Ascii85 encoded bytes-like object or ASCII string b.
  286. foldspaces is a flag that specifies whether the 'y' short sequence should be
  287. accepted as shorthand for 4 consecutive spaces (ASCII 0x20). This feature is
  288. not supported by the "standard" Adobe encoding.
  289. adobe controls whether the input sequence is in Adobe Ascii85 format (i.e.
  290. is framed with <~ and ~>).
  291. ignorechars should be a byte string containing characters to ignore from the
  292. input. This should only contain whitespace characters, and by default
  293. contains all whitespace characters in ASCII.
  294. The result is returned as a bytes object.
  295. """
  296. b = _bytes_from_decode_data(b)
  297. if adobe:
  298. if not b.endswith(_A85END):
  299. raise ValueError(
  300. "Ascii85 encoded byte sequences must end "
  301. "with {!r}".format(_A85END)
  302. )
  303. if b.startswith(_A85START):
  304. b = b[2:-2] # Strip off start/end markers
  305. else:
  306. b = b[:-2]
  307. #
  308. # We have to go through this stepwise, so as to ignore spaces and handle
  309. # special short sequences
  310. #
  311. packI = struct.Struct('!I').pack
  312. decoded = []
  313. decoded_append = decoded.append
  314. curr = []
  315. curr_append = curr.append
  316. curr_clear = curr.clear
  317. for x in b + b'u' * 4:
  318. if b'!'[0] <= x <= b'u'[0]:
  319. curr_append(x)
  320. if len(curr) == 5:
  321. acc = 0
  322. for x in curr:
  323. acc = 85 * acc + (x - 33)
  324. try:
  325. decoded_append(packI(acc))
  326. except struct.error:
  327. raise ValueError('Ascii85 overflow') from None
  328. curr_clear()
  329. elif x == b'z'[0]:
  330. if curr:
  331. raise ValueError('z inside Ascii85 5-tuple')
  332. decoded_append(b'\0\0\0\0')
  333. elif foldspaces and x == b'y'[0]:
  334. if curr:
  335. raise ValueError('y inside Ascii85 5-tuple')
  336. decoded_append(b'\x20\x20\x20\x20')
  337. elif x in ignorechars:
  338. # Skip whitespace
  339. continue
  340. else:
  341. raise ValueError('Non-Ascii85 digit found: %c' % x)
  342. result = b''.join(decoded)
  343. padding = 4 - len(curr)
  344. if padding:
  345. # Throw away the extra padding
  346. result = result[:-padding]
  347. return result
  348. # The following code is originally taken (with permission) from Mercurial
  349. _b85alphabet = (b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  350. b"abcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~")
  351. _b85chars = None
  352. _b85chars2 = None
  353. _b85dec = None
  354. def b85encode(b, pad=False):
  355. """Encode bytes-like object b in base85 format and return a bytes object.
  356. If pad is true, the input is padded with b'\\0' so its length is a multiple of
  357. 4 bytes before encoding.
  358. """
  359. global _b85chars, _b85chars2
  360. # Delay the initialization of tables to not waste memory
  361. # if the function is never called
  362. if _b85chars2 is None:
  363. _b85chars = [bytes((i,)) for i in _b85alphabet]
  364. _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]
  365. return _85encode(b, _b85chars, _b85chars2, pad)
  366. def b85decode(b):
  367. """Decode the base85-encoded bytes-like object or ASCII string b
  368. The result is returned as a bytes object.
  369. """
  370. global _b85dec
  371. # Delay the initialization of tables to not waste memory
  372. # if the function is never called
  373. if _b85dec is None:
  374. _b85dec = [None] * 256
  375. for i, c in enumerate(_b85alphabet):
  376. _b85dec[c] = i
  377. b = _bytes_from_decode_data(b)
  378. padding = (-len(b)) % 5
  379. b = b + b'~' * padding
  380. out = []
  381. packI = struct.Struct('!I').pack
  382. for i in range(0, len(b), 5):
  383. chunk = b[i:i + 5]
  384. acc = 0
  385. try:
  386. for c in chunk:
  387. acc = acc * 85 + _b85dec[c]
  388. except TypeError:
  389. for j, c in enumerate(chunk):
  390. if _b85dec[c] is None:
  391. raise ValueError('bad base85 character at position %d'
  392. % (i + j)) from None
  393. raise
  394. try:
  395. out.append(packI(acc))
  396. except struct.error:
  397. raise ValueError('base85 overflow in hunk starting at byte %d'
  398. % i) from None
  399. result = b''.join(out)
  400. if padding:
  401. result = result[:-padding]
  402. return result
  403. # Legacy interface. This code could be cleaned up since I don't believe
  404. # binascii has any line length limitations. It just doesn't seem worth it
  405. # though. The files should be opened in binary mode.
  406. MAXLINESIZE = 76 # Excluding the CRLF
  407. MAXBINSIZE = (MAXLINESIZE//4)*3
  408. def encode(input, output):
  409. """Encode a file; input and output are binary files."""
  410. while True:
  411. s = input.read(MAXBINSIZE)
  412. if not s:
  413. break
  414. while len(s) < MAXBINSIZE:
  415. ns = input.read(MAXBINSIZE-len(s))
  416. if not ns:
  417. break
  418. s += ns
  419. line = binascii.b2a_base64(s)
  420. output.write(line)
  421. def decode(input, output):
  422. """Decode a file; input and output are binary files."""
  423. while True:
  424. line = input.readline()
  425. if not line:
  426. break
  427. s = binascii.a2b_base64(line)
  428. output.write(s)
  429. def _input_type_check(s):
  430. try:
  431. m = memoryview(s)
  432. except TypeError as err:
  433. msg = "expected bytes-like object, not %s" % s.__class__.__name__
  434. raise TypeError(msg) from err
  435. if m.format not in ('c', 'b', 'B'):
  436. msg = ("expected single byte elements, not %r from %s" %
  437. (m.format, s.__class__.__name__))
  438. raise TypeError(msg)
  439. if m.ndim != 1:
  440. msg = ("expected 1-D data, not %d-D data from %s" %
  441. (m.ndim, s.__class__.__name__))
  442. raise TypeError(msg)
  443. def encodebytes(s):
  444. """Encode a bytestring into a bytes object containing multiple lines
  445. of base-64 data."""
  446. _input_type_check(s)
  447. pieces = []
  448. for i in range(0, len(s), MAXBINSIZE):
  449. chunk = s[i : i + MAXBINSIZE]
  450. pieces.append(binascii.b2a_base64(chunk))
  451. return b"".join(pieces)
  452. def decodebytes(s):
  453. """Decode a bytestring of base-64 data into a bytes object."""
  454. _input_type_check(s)
  455. return binascii.a2b_base64(s)
  456. # Usable as a script...
  457. def main():
  458. """Small main program"""
  459. import sys, getopt
  460. try:
  461. opts, args = getopt.getopt(sys.argv[1:], 'deut')
  462. except getopt.error as msg:
  463. sys.stdout = sys.stderr
  464. print(msg)
  465. print("""usage: %s [-d|-e|-u|-t] [file|-]
  466. -d, -u: decode
  467. -e: encode (default)
  468. -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0])
  469. sys.exit(2)
  470. func = encode
  471. for o, a in opts:
  472. if o == '-e': func = encode
  473. if o == '-d': func = decode
  474. if o == '-u': func = decode
  475. if o == '-t': test(); return
  476. if args and args[0] != '-':
  477. with open(args[0], 'rb') as f:
  478. func(f, sys.stdout.buffer)
  479. else:
  480. func(sys.stdin.buffer, sys.stdout.buffer)
  481. def test():
  482. s0 = b"Aladdin:open sesame"
  483. print(repr(s0))
  484. s1 = encodebytes(s0)
  485. print(repr(s1))
  486. s2 = decodebytes(s1)
  487. print(repr(s2))
  488. assert s0 == s2
  489. if __name__ == '__main__':
  490. main()