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