Back to index

python3.2  3.2.2
Functions | Variables
base64 Namespace Reference

Functions

def _translate
def b64encode
def b64decode
def standard_b64encode
def standard_b64decode
def urlsafe_b64encode
def urlsafe_b64decode
def b32encode
def b32decode
def b16encode
def b16decode
def encode
def decode
def encodebytes
def encodestring
def decodebytes
def decodestring
def main
def test

Variables

list __all__
tuple bytes_types = (bytes, bytearray)
dictionary _b32alphabet
list _b32tab = [v[0] for k, v in sorted(_b32alphabet.items())]
tuple _b32rev = dict([(v[0], k) for k, v in _b32alphabet.items()])
int MAXLINESIZE = 76
tuple MAXBINSIZE = (MAXLINESIZE//4)

Function Documentation

def base64._translate (   s,
  altchars 
) [private]

Definition at line 33 of file base64.py.

00033 
00034 def _translate(s, altchars):
00035     if not isinstance(s, bytes_types):
00036         raise TypeError("expected bytes, not %s" % s.__class__.__name__)
00037     translation = bytearray(range(256))
00038     for k, v in altchars.items():
00039         translation[ord(k)] = v[0]
00040     return s.translate(translation)
00041 
00042 
00043 
00044 # Base64 encoding/decoding uses binascii

Here is the call graph for this function:

Here is the caller graph for this function:

def base64.b16decode (   s,
  casefold = False 
)
Decode a Base16 encoded byte string.

s is the byte string to decode.  Optional casefold is a flag
specifying whether a lowercase alphabet is acceptable as input.
For security purposes, the default is False.

The decoded byte string is returned.  binascii.Error is raised if
s were incorrectly padded or if there are non-alphabet characters
present in the string.

Definition at line 284 of file base64.py.

00284 
00285 def b16decode(s, casefold=False):
00286     """Decode a Base16 encoded byte string.
00287 
00288     s is the byte string to decode.  Optional casefold is a flag
00289     specifying whether a lowercase alphabet is acceptable as input.
00290     For security purposes, the default is False.
00291 
00292     The decoded byte string is returned.  binascii.Error is raised if
00293     s were incorrectly padded or if there are non-alphabet characters
00294     present in the string.
00295     """
00296     if not isinstance(s, bytes_types):
00297         raise TypeError("expected bytes, not %s" % s.__class__.__name__)
00298     if casefold:
00299         s = s.upper()
00300     if re.search(b'[^0-9A-F]', s):
00301         raise binascii.Error('Non-base16 digit found')
00302     return binascii.unhexlify(s)
00303 
00304 
00305 
00306 # Legacy interface.  This code could be cleaned up since I don't believe
00307 # binascii has any line length limitations.  It just doesn't seem worth it
00308 # though.  The files should be opened in binary mode.

Here is the call graph for this function:

Here is the caller graph for this function:

def base64.b16encode (   s)
Encode a byte string using Base16.

s is the byte string to encode.  The encoded byte string is returned.

Definition at line 274 of file base64.py.

00274 
00275 def b16encode(s):
00276     """Encode a byte string using Base16.
00277 
00278     s is the byte string to encode.  The encoded byte string is returned.
00279     """
00280     if not isinstance(s, bytes_types):
00281         raise TypeError("expected bytes, not %s" % s.__class__.__name__)
00282     return binascii.hexlify(s).upper()
00283 

Here is the caller graph for this function:

def base64.b32decode (   s,
  casefold = False,
  map01 = None 
)
Decode a Base32 encoded byte string.

s is the byte string to decode.  Optional casefold is a flag
specifying whether a lowercase alphabet is acceptable as input.
For security purposes, the default is False.

RFC 3548 allows for optional mapping of the digit 0 (zero) to the
letter O (oh), and for optional mapping of the digit 1 (one) to
either the letter I (eye) or letter L (el).  The optional argument
map01 when not None, specifies which letter the digit 1 should be
mapped to (when map01 is not None, the digit 0 is always mapped to
the letter O).  For security purposes the default is None, so that
0 and 1 are not allowed in the input.

The decoded byte string is returned.  binascii.Error is raised if
the input is incorrectly padded or if there are non-alphabet
characters present in the input.

Definition at line 195 of file base64.py.

00195 
00196 def b32decode(s, casefold=False, map01=None):
00197     """Decode a Base32 encoded byte string.
00198 
00199     s is the byte string to decode.  Optional casefold is a flag
00200     specifying whether a lowercase alphabet is acceptable as input.
00201     For security purposes, the default is False.
00202 
00203     RFC 3548 allows for optional mapping of the digit 0 (zero) to the
00204     letter O (oh), and for optional mapping of the digit 1 (one) to
00205     either the letter I (eye) or letter L (el).  The optional argument
00206     map01 when not None, specifies which letter the digit 1 should be
00207     mapped to (when map01 is not None, the digit 0 is always mapped to
00208     the letter O).  For security purposes the default is None, so that
00209     0 and 1 are not allowed in the input.
00210 
00211     The decoded byte string is returned.  binascii.Error is raised if
00212     the input is incorrectly padded or if there are non-alphabet
00213     characters present in the input.
00214     """
00215     if not isinstance(s, bytes_types):
00216         raise TypeError("expected bytes, not %s" % s.__class__.__name__)
00217     quanta, leftover = divmod(len(s), 8)
00218     if leftover:
00219         raise binascii.Error('Incorrect padding')
00220     # Handle section 2.4 zero and one mapping.  The flag map01 will be either
00221     # False, or the character to map the digit 1 (one) to.  It should be
00222     # either L (el) or I (eye).
00223     if map01 is not None:
00224         if not isinstance(map01, bytes_types):
00225             raise TypeError("expected bytes, not %s" % map01.__class__.__name__)
00226         assert len(map01) == 1, repr(map01)
00227         s = _translate(s, {b'0': b'O', b'1': map01})
00228     if casefold:
00229         s = s.upper()
00230     # Strip off pad characters from the right.  We need to count the pad
00231     # characters because this will tell us how many null bytes to remove from
00232     # the end of the decoded string.
00233     padchars = 0
00234     mo = re.search(b'(?P<pad>[=]*)$', s)
00235     if mo:
00236         padchars = len(mo.group('pad'))
00237         if padchars > 0:
00238             s = s[:-padchars]
00239     # Now decode the full quanta
00240     parts = []
00241     acc = 0
00242     shift = 35
00243     for c in s:
00244         val = _b32rev.get(c)
00245         if val is None:
00246             raise TypeError('Non-base32 digit found')
00247         acc += _b32rev[c] << shift
00248         shift -= 5
00249         if shift < 0:
00250             parts.append(binascii.unhexlify(bytes('%010x' % acc, "ascii")))
00251             acc = 0
00252             shift = 35
00253     # Process the last, partial quanta
00254     last = binascii.unhexlify(bytes('%010x' % acc, "ascii"))
00255     if padchars == 0:
00256         last = b''                      # No characters
00257     elif padchars == 1:
00258         last = last[:-1]
00259     elif padchars == 3:
00260         last = last[:-2]
00261     elif padchars == 4:
00262         last = last[:-3]
00263     elif padchars == 6:
00264         last = last[:-4]
00265     else:
00266         raise binascii.Error('Incorrect padding')
00267     parts.append(last)
00268     return b''.join(parts)
00269 
00270 
00271 
00272 # RFC 3548, Base 16 Alphabet specifies uppercase, but hexlify() returns
00273 # lowercase.  The RFC also recommends against accepting input case
# insensitively.

Here is the call graph for this function:

Here is the caller graph for this function:

def base64.b32encode (   s)
Encode a byte string using Base32.

s is the byte string to encode.  The encoded byte string is returned.

Definition at line 152 of file base64.py.

00152 
00153 def b32encode(s):
00154     """Encode a byte string using Base32.
00155 
00156     s is the byte string to encode.  The encoded byte string is returned.
00157     """
00158     if not isinstance(s, bytes_types):
00159         raise TypeError("expected bytes, not %s" % s.__class__.__name__)
00160     quanta, leftover = divmod(len(s), 5)
00161     # Pad the last quantum with zero bits if necessary
00162     if leftover:
00163         s = s + bytes(5 - leftover)  # Don't use += !
00164         quanta += 1
00165     encoded = bytes()
00166     for i in range(quanta):
00167         # c1 and c2 are 16 bits wide, c3 is 8 bits wide.  The intent of this
00168         # code is to process the 40 bits in units of 5 bits.  So we take the 1
00169         # leftover bit of c1 and tack it onto c2.  Then we take the 2 leftover
00170         # bits of c2 and tack them onto c3.  The shifts and masks are intended
00171         # to give us values of exactly 5 bits in width.
00172         c1, c2, c3 = struct.unpack('!HHB', s[i*5:(i+1)*5])
00173         c2 += (c1 & 1) << 16 # 17 bits wide
00174         c3 += (c2 & 3) << 8  # 10 bits wide
00175         encoded += bytes([_b32tab[c1 >> 11],         # bits 1 - 5
00176                           _b32tab[(c1 >> 6) & 0x1f], # bits 6 - 10
00177                           _b32tab[(c1 >> 1) & 0x1f], # bits 11 - 15
00178                           _b32tab[c2 >> 12],         # bits 16 - 20 (1 - 5)
00179                           _b32tab[(c2 >> 7) & 0x1f], # bits 21 - 25 (6 - 10)
00180                           _b32tab[(c2 >> 2) & 0x1f], # bits 26 - 30 (11 - 15)
00181                           _b32tab[c3 >> 5],          # bits 31 - 35 (1 - 5)
00182                           _b32tab[c3 & 0x1f],        # bits 36 - 40 (1 - 5)
00183                           ])
00184     # Adjust for any leftover partial quanta
00185     if leftover == 1:
00186         return encoded[:-6] + b'======'
00187     elif leftover == 2:
00188         return encoded[:-4] + b'===='
00189     elif leftover == 3:
00190         return encoded[:-3] + b'==='
00191     elif leftover == 4:
00192         return encoded[:-1] + b'='
00193     return encoded
00194 

Here is the call graph for this function:

Here is the caller graph for this function:

def base64.b64decode (   s,
  altchars = None,
  validate = False 
)
Decode a Base64 encoded byte string.

s is the byte string to decode.  Optional altchars must be a
string of length 2 which specifies the alternative alphabet used
instead of the '+' and '/' characters.

The decoded string is returned.  A binascii.Error is raised if s is
incorrectly padded.

If validate is False (the default), non-base64-alphabet characters are
discarded prior to the padding check.  If validate is True,
non-base64-alphabet characters in the input result in a binascii.Error.

Definition at line 68 of file base64.py.

00068 
00069 def b64decode(s, altchars=None, validate=False):
00070     """Decode a Base64 encoded byte string.
00071 
00072     s is the byte string to decode.  Optional altchars must be a
00073     string of length 2 which specifies the alternative alphabet used
00074     instead of the '+' and '/' characters.
00075 
00076     The decoded string is returned.  A binascii.Error is raised if s is
00077     incorrectly padded.
00078 
00079     If validate is False (the default), non-base64-alphabet characters are
00080     discarded prior to the padding check.  If validate is True,
00081     non-base64-alphabet characters in the input result in a binascii.Error.
00082     """
00083     if not isinstance(s, bytes_types):
00084         raise TypeError("expected bytes, not %s" % s.__class__.__name__)
00085     if altchars is not None:
00086         if not isinstance(altchars, bytes_types):
00087             raise TypeError("expected bytes, not %s"
00088                             % altchars.__class__.__name__)
00089         assert len(altchars) == 2, repr(altchars)
00090         s = _translate(s, {chr(altchars[0]): b'+', chr(altchars[1]): b'/'})
00091     if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
00092         raise binascii.Error('Non-base64 digit found')
00093     return binascii.a2b_base64(s)
00094 

Here is the call graph for this function:

Here is the caller graph for this function:

def base64.b64encode (   s,
  altchars = None 
)
Encode a byte string using Base64.

s is the byte string to encode.  Optional altchars must be a byte
string of length 2 which specifies an alternative alphabet for the
'+' and '/' characters.  This allows an application to
e.g. generate url or filesystem safe Base64 strings.

The encoded byte string is returned.

Definition at line 45 of file base64.py.

00045 
00046 def b64encode(s, altchars=None):
00047     """Encode a byte string using Base64.
00048 
00049     s is the byte string to encode.  Optional altchars must be a byte
00050     string of length 2 which specifies an alternative alphabet for the
00051     '+' and '/' characters.  This allows an application to
00052     e.g. generate url or filesystem safe Base64 strings.
00053 
00054     The encoded byte string is returned.
00055     """
00056     if not isinstance(s, bytes_types):
00057         raise TypeError("expected bytes, not %s" % s.__class__.__name__)
00058     # Strip off the trailing newline
00059     encoded = binascii.b2a_base64(s)[:-1]
00060     if altchars is not None:
00061         if not isinstance(altchars, bytes_types):
00062             raise TypeError("expected bytes, not %s"
00063                             % altchars.__class__.__name__)
00064         assert len(altchars) == 2, repr(altchars)
00065         return _translate(encoded, {'+': altchars[0:1], '/': altchars[1:2]})
00066     return encoded
00067 

Here is the call graph for this function:

Here is the caller graph for this function:

def base64.decode (   input,
  output 
)
Decode a file; input and output are binary files.

Definition at line 327 of file base64.py.

00327 
00328 def decode(input, output):
00329     """Decode a file; input and output are binary files."""
00330     while True:
00331         line = input.readline()
00332         if not line:
00333             break
00334         s = binascii.a2b_base64(line)
00335         output.write(s)
00336 

def base64.decodebytes (   s)
Decode a bytestring of base-64 data into a bytestring.

Definition at line 356 of file base64.py.

00356 
00357 def decodebytes(s):
00358     """Decode a bytestring of base-64 data into a bytestring."""
00359     if not isinstance(s, bytes_types):
00360         raise TypeError("expected bytes, not %s" % s.__class__.__name__)
00361     return binascii.a2b_base64(s)

Here is the caller graph for this function:

def base64.decodestring (   s)
Legacy alias of decodebytes().

Definition at line 362 of file base64.py.

00362 
00363 def decodestring(s):
00364     """Legacy alias of decodebytes()."""
00365     import warnings
00366     warnings.warn("decodestring() is a deprecated alias, use decodebytes()",
00367                   DeprecationWarning, 2)
00368     return decodebytes(s)
00369 
00370 
# Usable as a script...

Here is the call graph for this function:

def base64.encode (   input,
  output 
)
Encode a file; input and output are binary files.

Definition at line 312 of file base64.py.

00312 
00313 def encode(input, output):
00314     """Encode a file; input and output are binary files."""
00315     while True:
00316         s = input.read(MAXBINSIZE)
00317         if not s:
00318             break
00319         while len(s) < MAXBINSIZE:
00320             ns = input.read(MAXBINSIZE-len(s))
00321             if not ns:
00322                 break
00323             s += ns
00324         line = binascii.b2a_base64(s)
00325         output.write(line)
00326 

Here is the caller graph for this function:

def base64.encodebytes (   s)
Encode a bytestring into a bytestring containing multiple lines
of base-64 data.

Definition at line 337 of file base64.py.

00337 
00338 def encodebytes(s):
00339     """Encode a bytestring into a bytestring containing multiple lines
00340     of base-64 data."""
00341     if not isinstance(s, bytes_types):
00342         raise TypeError("expected bytes, not %s" % s.__class__.__name__)
00343     pieces = []
00344     for i in range(0, len(s), MAXBINSIZE):
00345         chunk = s[i : i + MAXBINSIZE]
00346         pieces.append(binascii.b2a_base64(chunk))
00347     return b"".join(pieces)

Here is the caller graph for this function:

def base64.encodestring (   s)
Legacy alias of encodebytes().

Definition at line 348 of file base64.py.

00348 
00349 def encodestring(s):
00350     """Legacy alias of encodebytes()."""
00351     import warnings
00352     warnings.warn("encodestring() is a deprecated alias, use encodebytes()",
00353                   DeprecationWarning, 2)
00354     return encodebytes(s)
00355 

Here is the call graph for this function:

def base64.main ( void  )
Small main program

Definition at line 371 of file base64.py.

00371 
00372 def main():
00373     """Small main program"""
00374     import sys, getopt
00375     try:
00376         opts, args = getopt.getopt(sys.argv[1:], 'deut')
00377     except getopt.error as msg:
00378         sys.stdout = sys.stderr
00379         print(msg)
00380         print("""usage: %s [-d|-e|-u|-t] [file|-]
00381         -d, -u: decode
00382         -e: encode (default)
00383         -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0])
00384         sys.exit(2)
00385     func = encode
00386     for o, a in opts:
00387         if o == '-e': func = encode
00388         if o == '-d': func = decode
00389         if o == '-u': func = decode
00390         if o == '-t': test(); return
00391     if args and args[0] != '-':
00392         with open(args[0], 'rb') as f:
00393             func(f, sys.stdout.buffer)
00394     else:
00395         func(sys.stdin.buffer, sys.stdout.buffer)
00396 

Here is the call graph for this function:

Here is the caller graph for this function:

Decode a byte string encoded with the standard Base64 alphabet.

s is the byte string to decode.  The decoded byte string is
returned.  binascii.Error is raised if the input is incorrectly
padded or if there are non-alphabet characters present in the
input.

Definition at line 102 of file base64.py.

00102 
00103 def standard_b64decode(s):
00104     """Decode a byte string encoded with the standard Base64 alphabet.
00105 
00106     s is the byte string to decode.  The decoded byte string is
00107     returned.  binascii.Error is raised if the input is incorrectly
00108     padded or if there are non-alphabet characters present in the
00109     input.
00110     """
00111     return b64decode(s)

Here is the call graph for this function:

Here is the caller graph for this function:

Encode a byte string using the standard Base64 alphabet.

s is the byte string to encode.  The encoded byte string is returned.

Definition at line 95 of file base64.py.

00095 
00096 def standard_b64encode(s):
00097     """Encode a byte string using the standard Base64 alphabet.
00098 
00099     s is the byte string to encode.  The encoded byte string is returned.
00100     """
00101     return b64encode(s)

Here is the call graph for this function:

Here is the caller graph for this function:

def base64.test ( )

Definition at line 397 of file base64.py.

00397 
00398 def test():
00399     s0 = b"Aladdin:open sesame"
00400     print(repr(s0))
00401     s1 = encodebytes(s0)
00402     print(repr(s1))
00403     s2 = decodebytes(s1)
00404     print(repr(s2))
00405     assert s0 == s2
00406 

Here is the call graph for this function:

Decode a byte string encoded with the standard Base64 alphabet.

s is the byte string to decode.  The decoded byte string is
returned.  binascii.Error is raised if the input is incorrectly
padded or if there are non-alphabet characters present in the
input.

The alphabet uses '-' instead of '+' and '_' instead of '/'.

Definition at line 121 of file base64.py.

00121 
00122 def urlsafe_b64decode(s):
00123     """Decode a byte string encoded with the standard Base64 alphabet.
00124 
00125     s is the byte string to decode.  The decoded byte string is
00126     returned.  binascii.Error is raised if the input is incorrectly
00127     padded or if there are non-alphabet characters present in the
00128     input.
00129 
00130     The alphabet uses '-' instead of '+' and '_' instead of '/'.
00131     """
00132     return b64decode(s, b'-_')
00133 
00134 
00135 
# Base32 encoding/decoding must be done in Python

Here is the call graph for this function:

Here is the caller graph for this function:

Encode a byte string using a url-safe Base64 alphabet.

s is the byte string to encode.  The encoded byte string is
returned.  The alphabet uses '-' instead of '+' and '_' instead of
'/'.

Definition at line 112 of file base64.py.

00112 
00113 def urlsafe_b64encode(s):
00114     """Encode a byte string using a url-safe Base64 alphabet.
00115 
00116     s is the byte string to encode.  The encoded byte string is
00117     returned.  The alphabet uses '-' instead of '+' and '_' instead of
00118     '/'.
00119     """
00120     return b64encode(s, b'-_')

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 [
00002     # Legacy interface exports traditional RFC 1521 Base64 encodings
00003     'encode', 'decode', 'encodebytes', 'decodebytes',
00004     # Generalized interface for other encodings
00005     'b64encode', 'b64decode', 'b32encode', 'b32decode',
00006     'b16encode', 'b16decode',
00007     # Standard Base64 encoding
00008     'standard_b64encode', 'standard_b64decode',
00009     # Some common Base64 alternatives.  As referenced by RFC 3458, see thread
00010     # starting at:
00011     #
00012     # http://zgp.org/pipermail/p2p-hackers/2001-September/000316.html
00013     'urlsafe_b64encode', 'urlsafe_b64decode',
00014     ]

Definition at line 14 of file base64.py.

Initial value:
00001 {
00002     0: b'A',  9: b'J', 18: b'S', 27: b'3',
00003     1: b'B', 10: b'K', 19: b'T', 28: b'4',
00004     2: b'C', 11: b'L', 20: b'U', 29: b'5',
00005     3: b'D', 12: b'M', 21: b'V', 30: b'6',
00006     4: b'E', 13: b'N', 22: b'W', 31: b'7',
00007     5: b'F', 14: b'O', 23: b'X',
00008     6: b'G', 15: b'P', 24: b'Y',
00009     7: b'H', 16: b'Q', 25: b'Z',
00010     8: b'I', 17: b'R', 26: b'2',
00011     }

Definition at line 136 of file base64.py.

tuple base64._b32rev = dict([(v[0], k) for k, v in _b32alphabet.items()])

Definition at line 149 of file base64.py.

list base64._b32tab = [v[0] for k, v in sorted(_b32alphabet.items())]

Definition at line 148 of file base64.py.

tuple base64.bytes_types = (bytes, bytearray)

Definition at line 30 of file base64.py.

Definition at line 310 of file base64.py.

Definition at line 309 of file base64.py.