Python base64.b32decode() Examples

The following are 30 code examples for showing how to use base64.b32decode(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module base64 , or try the search function .

Example 1
Project: browserscope   Author: elsigh   File: api_config_manager.py    License: Apache License 2.0 6 votes vote down vote up
def _from_safe_path_param_name(safe_parameter):
    """Takes a safe regex group name and converts it back to the original value.

    Only alphanumeric characters and underscore are allowed in variable name
    tokens, and numeric are not allowed as the first character.

    The safe_parameter is a base32 representation of the actual value.

    Args:
      safe_parameter: A string that was generated by _to_safe_path_param_name.

    Returns:
      A string, the parameter matched from the URL template.
    """
    assert safe_parameter.startswith('_')
    safe_parameter_as_base32 = safe_parameter[1:]

    padding_length = - len(safe_parameter_as_base32) % 8
    padding = '=' * padding_length
    return base64.b32decode(safe_parameter_as_base32 + padding) 
Example 2
Project: browserscope   Author: elsigh   File: dev_appserver_apiserver.py    License: Apache License 2.0 6 votes vote down vote up
def _FromSafePathParamName(safe_parameter):
    """Takes a safe regex group name and converts it back to the original value.

    Only alphanumeric characters and underscore are allowed in variable name
    tokens, and numeric are not allowed as the first character.

    The safe_parameter is a base32 representation of the actual value.

    Args:
      safe_parameter: String, safe regex group name.

    Returns:
      String; parameter matched from URL template.
    """
    assert safe_parameter.startswith('_')
    safe_parameter_as_base32 = safe_parameter[1:]

    padding_length = - len(safe_parameter_as_base32) % 8
    padding = '=' * padding_length
    return base64.b32decode(safe_parameter_as_base32 + padding) 
Example 3
Project: endpoints-python   Author: cloudendpoints   File: api_config_manager.py    License: Apache License 2.0 6 votes vote down vote up
def _from_safe_path_param_name(safe_parameter):
    """Takes a safe regex group name and converts it back to the original value.

    Only alphanumeric characters and underscore are allowed in variable name
    tokens, and numeric are not allowed as the first character.

    The safe_parameter is a base32 representation of the actual value.

    Args:
      safe_parameter: A string that was generated by _to_safe_path_param_name.

    Returns:
      A string, the parameter matched from the URL template.
    """
    assert safe_parameter.startswith('_')
    safe_parameter_as_base32 = safe_parameter[1:]

    padding_length = - len(safe_parameter_as_base32) % 8
    padding = '=' * padding_length
    return base64.b32decode(safe_parameter_as_base32 + padding) 
Example 4
Project: king-phisher   Author: rsmusllp   File: templates.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _filter_decode(self, data, encoding):
		if its.py_v3 and isinstance(data, bytes):
			data = data.decode('utf-8')
		encoding = encoding.lower()
		encoding = re.sub(r'^(base|rot)-(\d\d)$', r'\1\2', encoding)

		if encoding == 'base16' or encoding == 'hex':
			data = base64.b16decode(data)
		elif encoding == 'base32':
			data = base64.b32decode(data)
		elif encoding == 'base64':
			data = base64.b64decode(data)
		elif encoding == 'rot13':
			data = codecs.getdecoder('rot-13')(data)[0]
		else:
			raise ValueError('Unknown encoding type: ' + encoding)
		if its.py_v3 and isinstance(data, bytes):
			data = data.decode('utf-8')
		return data 
Example 5
Project: torf   Author: rndusr   File: _magnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def torrent(self):
        """:class:`Torrent` instance"""
        # Prevent circular import issues
        from ._torrent import Torrent
        torrent = Torrent()
        torrent.name = self.dn
        if self.tr:
            torrent.trackers = self.tr
        if self.ws:
            torrent.webseeds = self.ws
        if self.xl:
            torrent._metainfo['info']['length'] = self.xl
        if hasattr(self, '_info'):
            torrent.metainfo['info'] = self._info
        elif len(self.infohash) == 40:
            torrent._infohash = self.infohash
        else:
            # Convert base 32 to base 16 (SHA1)
            torrent._infohash = base64.b16encode(
                base64.b32decode(self.infohash)).decode('utf-8').lower()
        return torrent 
Example 6
Project: ironpython2   Author: IronLanguages   File: test_base64.py    License: Apache License 2.0 6 votes vote down vote up
def test_b32decode_casefold(self):
        eq = self.assertEqual
        eq(base64.b32decode('', True), '')
        eq(base64.b32decode('ME======', True), 'a')
        eq(base64.b32decode('MFRA====', True), 'ab')
        eq(base64.b32decode('MFRGG===', True), 'abc')
        eq(base64.b32decode('MFRGGZA=', True), 'abcd')
        eq(base64.b32decode('MFRGGZDF', True), 'abcde')
        # Lower cases
        eq(base64.b32decode('me======', True), 'a')
        eq(base64.b32decode('mfra====', True), 'ab')
        eq(base64.b32decode('mfrgg===', True), 'abc')
        eq(base64.b32decode('mfrggza=', True), 'abcd')
        eq(base64.b32decode('mfrggzdf', True), 'abcde')
        # Expected exceptions
        self.assertRaises(TypeError, base64.b32decode, 'me======')
        # Mapping zero and one
        eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe')
        eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe')
        eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe') 
Example 7
Project: BinderFilter   Author: dxwu   File: test_base64.py    License: MIT License 6 votes vote down vote up
def test_b32decode_casefold(self):
        eq = self.assertEqual
        eq(base64.b32decode('', True), '')
        eq(base64.b32decode('ME======', True), 'a')
        eq(base64.b32decode('MFRA====', True), 'ab')
        eq(base64.b32decode('MFRGG===', True), 'abc')
        eq(base64.b32decode('MFRGGZA=', True), 'abcd')
        eq(base64.b32decode('MFRGGZDF', True), 'abcde')
        # Lower cases
        eq(base64.b32decode('me======', True), 'a')
        eq(base64.b32decode('mfra====', True), 'ab')
        eq(base64.b32decode('mfrgg===', True), 'abc')
        eq(base64.b32decode('mfrggza=', True), 'abcd')
        eq(base64.b32decode('mfrggzdf', True), 'abcde')
        # Expected exceptions
        self.assertRaises(TypeError, base64.b32decode, 'me======')
        # Mapping zero and one
        eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe')
        eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe')
        eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe') 
Example 8
Project: oss-ftp   Author: aliyun   File: test_base64.py    License: MIT License 6 votes vote down vote up
def test_b32decode_casefold(self):
        eq = self.assertEqual
        eq(base64.b32decode('', True), '')
        eq(base64.b32decode('ME======', True), 'a')
        eq(base64.b32decode('MFRA====', True), 'ab')
        eq(base64.b32decode('MFRGG===', True), 'abc')
        eq(base64.b32decode('MFRGGZA=', True), 'abcd')
        eq(base64.b32decode('MFRGGZDF', True), 'abcde')
        # Lower cases
        eq(base64.b32decode('me======', True), 'a')
        eq(base64.b32decode('mfra====', True), 'ab')
        eq(base64.b32decode('mfrgg===', True), 'abc')
        eq(base64.b32decode('mfrggza=', True), 'abcd')
        eq(base64.b32decode('mfrggzdf', True), 'abcde')
        # Expected exceptions
        self.assertRaises(TypeError, base64.b32decode, 'me======')
        # Mapping zero and one
        eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe')
        eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe')
        eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe') 
Example 9
Project: aws-security-automation   Author: awslabs   File: ForceUserMFA.py    License: Apache License 2.0 6 votes vote down vote up
def generate_token(seed):
    """Summary

    Args:
        seed (TYPE): Description

    Returns:
        TYPE: Description
    """
    seed = base64.b32decode(seed, True)
    hmacHash = hmac.new(
        seed, struct.pack(
            ">Q", int(
                time.time() // 30)),
        hashlib.sha1).digest()
    hashOffset = ord(hmacHash[19]) & 0xf
    token = (struct.unpack(
        ">I",
        hmacHash[hashOffset:hashOffset + 4])[0] & 0x7fffffff) % 10 ** 6
    return token 
Example 10
Project: Fluid-Designer   Author: Microvellum   File: test_base64.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_b32decode(self):
        eq = self.assertEqual
        tests = {b'': b'',
                 b'AA======': b'\x00',
                 b'ME======': b'a',
                 b'MFRA====': b'ab',
                 b'MFRGG===': b'abc',
                 b'MFRGGZA=': b'abcd',
                 b'MFRGGZDF': b'abcde',
                 }
        for data, res in tests.items():
            eq(base64.b32decode(data), res)
            eq(base64.b32decode(data.decode('ascii')), res)
        # Non-bytes
        self.check_other_types(base64.b32decode, b'MFRGG===', b"abc")
        self.check_decode_type_errors(base64.b32decode) 
Example 11
Project: anvio   Author: merenlab   File: bottleroutes.py    License: GNU General Public License v3.0 6 votes vote down vote up
def reroot_tree(self):
        newick = request.forms.get('newick')
        tree = Tree(newick, format=1)

        left_most = tree.search_nodes(name=request.forms.get('left_most'))[0]
        right_most = tree.search_nodes(name=request.forms.get('right_most'))[0]

        new_root = tree.get_common_ancestor(left_most, right_most)
        tree.set_outgroup(new_root)

        # Ete3 tree.write function replaces some charachters that we support in the interface.
        # As a workaround we are going to encode node names with base32, after serialization
        # we are going to decode them back.
        for node in tree.traverse('preorder'):
            node.name = 'base32' + base64.b32encode(node.name.encode('utf-8')).decode('utf-8')

        new_newick = tree.write(format=1)

        # ete also converts base32 padding charachter "=" to "_" so we need to replace it.
        new_newick = re.sub(r"base32(\w*)", lambda m: base64.b32decode(m.group(1).replace('_','=')).decode('utf-8'), new_newick)

        return json.dumps({'newick': new_newick}) 
Example 12
Project: ironpython3   Author: IronLanguages   File: test_base64.py    License: Apache License 2.0 6 votes vote down vote up
def test_b32decode(self):
        eq = self.assertEqual
        tests = {b'': b'',
                 b'AA======': b'\x00',
                 b'ME======': b'a',
                 b'MFRA====': b'ab',
                 b'MFRGG===': b'abc',
                 b'MFRGGZA=': b'abcd',
                 b'MFRGGZDF': b'abcde',
                 }
        for data, res in tests.items():
            eq(base64.b32decode(data), res)
            eq(base64.b32decode(data.decode('ascii')), res)
        # Non-bytes
        self.check_other_types(base64.b32decode, b'MFRGG===', b"abc")
        self.check_decode_type_errors(base64.b32decode) 
Example 13
Project: NeuralResponseRanking   Author: yangliuy   File: rank_io.py    License: MIT License 6 votes vote down vote up
def read_qa_comat(filename):
    qa_comat_dict = {}
    print 'read qa_comat ...'
    with open(filename) as fin:
        for l in tqdm(fin):
            to = l.strip().split('\t')
            #print 'test len(to): ', len(to)
            m = np.loads(base64.b32decode(to[1]))
            # print 'test m: ', m
            # to[0] key which is qid_uid_rid; to[1] is the corresponding
            # 3-row numpy array to denote the qa co-occur matrix
            m0 = np.asarray(m[0], dtype=np.int16)
            m1 = np.asarray(m[1], dtype=np.int16)
            qa_comat_dict[to[0]] = [m0,m1,m[2]]
    return qa_comat_dict

# Convert Embedding Dict 2 numpy array 
Example 14
Project: collection   Author: skywind3000   File: googauth.py    License: MIT License 6 votes vote down vote up
def generate_code(secret, value = None):
	if value is None:
		value = int(time.time() / 30)
	value = struct.pack('>q', value)

	secretkey = base64.b32decode(secret.upper())

	hash = hmac.new(secretkey, value, hashlib.sha1).digest()

	offset = struct.unpack('>B', hash[-1:])[0] & 0xf
	truncated_hash = hash[offset:offset + 4]

	truncated_hash = struct.unpack('>L', truncated_hash)[0]
	truncated_hash &= 0x7fffffff
	truncated_hash %= 1000000

	return '%06d' % truncated_hash


#----------------------------------------------------------------------
# counter based code varification
#---------------------------------------------------------------------- 
Example 15
Project: qrtun   Author: seiferteric   File: qrtun_async.py    License: MIT License 6 votes vote down vote up
def read_qrcode(self):
        p = subprocess.Popen(['zbarimg', '-q', '--raw', 'PNG:-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        temp_png = StringIO.StringIO()
        self.inframe.save(temp_png, 'png')
        std_out, std_err = p.communicate(input=temp_png.getvalue())
        if len(std_out) == 0:
            return False

        if std_err:
            raise Exception("zbarimg", std_err.strip())
        #p = subprocess.Popen(['iconv', '-f', 'UTF-8', '-t', 'ISO-8859-1'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        #std_out, std_err = p.communicate(input=std_out)
        #if std_err:
        #    raise Exception("iconv", std_err.strip())
        try:
            self.indata = {'body': b32decode(std_out.rstrip().replace('/', '='))}
            self.write_tun()
        except:
            pass 
Example 16
Project: gcblue   Author: gcblue   File: test_base64.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_b32decode_casefold(self):
        eq = self.assertEqual
        eq(base64.b32decode('', True), '')
        eq(base64.b32decode('ME======', True), 'a')
        eq(base64.b32decode('MFRA====', True), 'ab')
        eq(base64.b32decode('MFRGG===', True), 'abc')
        eq(base64.b32decode('MFRGGZA=', True), 'abcd')
        eq(base64.b32decode('MFRGGZDF', True), 'abcde')
        # Lower cases
        eq(base64.b32decode('me======', True), 'a')
        eq(base64.b32decode('mfra====', True), 'ab')
        eq(base64.b32decode('mfrgg===', True), 'abc')
        eq(base64.b32decode('mfrggza=', True), 'abcd')
        eq(base64.b32decode('mfrggzdf', True), 'abcde')
        # Expected exceptions
        self.assertRaises(TypeError, base64.b32decode, 'me======')
        # Mapping zero and one
        eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe')
        eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe')
        eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe') 
Example 17
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: api_config_manager.py    License: Apache License 2.0 6 votes vote down vote up
def _from_safe_path_param_name(safe_parameter):
    """Takes a safe regex group name and converts it back to the original value.

    Only alphanumeric characters and underscore are allowed in variable name
    tokens, and numeric are not allowed as the first character.

    The safe_parameter is a base32 representation of the actual value.

    Args:
      safe_parameter: A string that was generated by _to_safe_path_param_name.

    Returns:
      A string, the parameter matched from the URL template.
    """
    assert safe_parameter.startswith('_')
    safe_parameter_as_base32 = safe_parameter[1:]

    padding_length = - len(safe_parameter_as_base32) % 8
    padding = '=' * padding_length
    return base64.b32decode(safe_parameter_as_base32 + padding) 
Example 18
Project: hermit   Author: unchained-capital   File: format.py    License: Apache License 2.0 6 votes vote down vote up
def decode_qr_code_data(encoded: bytes) -> str:
    if not isinstance(encoded, (bytes,)):
        raise InvalidSignatureRequest("Can only decode bytes")
    if encoded == b'':
        raise InvalidSignatureRequest("Cannot decode empty bytes")
    try:
        compressed_bytes = b32decode(encoded)
        try:
            decompressed_bytes = decompress(compressed_bytes)
            try:
                data = decompressed_bytes.decode('utf-8')
                return data
            except UnicodeError:
                raise InvalidSignatureRequest("Not valid UTF-8")
        except OSError:
            raise InvalidSignatureRequest("Not gzipped")
    except (TypeError, Base32DecodeError):
        raise InvalidSignatureRequest("Not Base32") 
Example 19
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_base64.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_b32decode(self):
        eq = self.assertEqual
        tests = {b'': b'',
                 b'AA======': b'\x00',
                 b'ME======': b'a',
                 b'MFRA====': b'ab',
                 b'MFRGG===': b'abc',
                 b'MFRGGZA=': b'abcd',
                 b'MFRGGZDF': b'abcde',
                 }
        for data, res in tests.items():
            eq(base64.b32decode(data), res)
            eq(base64.b32decode(data.decode('ascii')), res)
        # Non-bytes
        self.check_other_types(base64.b32decode, b'MFRGG===', b"abc")
        self.check_decode_type_errors(base64.b32decode) 
Example 20
Project: XFLTReaT   Author: earthquake   File: encoding.py    License: MIT License 5 votes vote down vote up
def decode(self, text):
		if len(text) % 8:
			text += "="*(8-(len(text)%8))
		try:
			return base64.b32decode(text.upper())
		except:
			return "" 
Example 21
Project: pycoind   Author: ricmoo   File: piecewise.py    License: MIT License 5 votes vote down vote up
def partial_split_qr_decode(qr_code):
    'Decode a partial key-set QR code.'

    # calculate padding that would have been stripped
    padding = (len(qr_code) * 5 - 9 * 8) % 32
    binary = base64.b32decode(qr_code + ('=' * padding))

    # check the header
    if not binary.startswith('\x84\x7c\x20'):
        raise ValueError('invalid header')

    # the missing index for this set
    missing = ord(binary[3])

    required = ord(binary[4])
    checksum = binary[5:9]

    # extract each binary key and recompose the key
    keys = set()
    start = 9
    index = 0
    while start + 32 <= len(binary):
        if index == missing: index += 1
        key = '\x10\x01' + chr(index) + chr(required) + checksum + binary[start:start + 32]
        keys.add(encode_check(key))
        start += 32
        index += 1

    return keys 
Example 22
Project: stem   Author: torproject   File: hidden_service.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def identity_key_from_address(onion_address: str) -> bytes:
    """
    Converts a hidden service address into its public identity key.

    :param onion_address: hidden service address

    :returns: **bytes** for the hidden service's public identity key

    :raises: **ValueError** if address malformed or checksum is invalid
    """

    if onion_address.endswith('.onion'):
      onion_address = onion_address[:-6]

    if not stem.util.tor_tools.is_valid_hidden_service_address(onion_address, version = 3):
      raise ValueError("'%s.onion' isn't a valid hidden service v3 address" % onion_address)

    # onion_address = base32(PUBKEY | CHECKSUM | VERSION) + '.onion'
    # CHECKSUM = H('.onion checksum' | PUBKEY | VERSION)[:2]

    decoded_address = base64.b32decode(onion_address.upper())

    pubkey = decoded_address[:32]
    expected_checksum = decoded_address[32:34]
    version = decoded_address[34:35]

    checksum = hashlib.sha3_256(CHECKSUM_CONSTANT + pubkey + version).digest()[:2]

    if expected_checksum != checksum:
      checksum_str = stem.util.str_tools._to_unicode(binascii.hexlify(checksum))
      expected_checksum_str = stem.util.str_tools._to_unicode(binascii.hexlify(expected_checksum))

      raise ValueError('Bad checksum (expected %s but was %s)' % (expected_checksum_str, checksum_str))

    return pubkey 
Example 23
Project: ironpython2   Author: IronLanguages   File: test_base64.py    License: Apache License 2.0 5 votes vote down vote up
def test_b32decode(self):
        eq = self.assertEqual
        eq(base64.b32decode(''), '')
        eq(base64.b32decode('AA======'), '\x00')
        eq(base64.b32decode('ME======'), 'a')
        eq(base64.b32decode('MFRA===='), 'ab')
        eq(base64.b32decode('MFRGG==='), 'abc')
        eq(base64.b32decode('MFRGGZA='), 'abcd')
        eq(base64.b32decode('MFRGGZDF'), 'abcde')
        # Non-bytes
        self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG===')) 
Example 24
Project: ironpython2   Author: IronLanguages   File: test_base64.py    License: Apache License 2.0 5 votes vote down vote up
def test_b32decode_error(self):
        self.assertRaises(TypeError, base64.b32decode, 'abc')
        self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') 
Example 25
def _base32_decode(self, decode_string):
        decoder = base64.b32decode(decode_string, casefol=False, map01=None)
        return decoder 
Example 26
Project: privacyidea   Author: privacyidea   File: __init__.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def decode_base32check(encoded_data, always_upper=True):
    """
    Decode arbitrary data which is given in the following format::

        strip_padding(base32(sha1(payload)[:4] + payload))

    Raise a ParameterError if the encoded payload is malformed.
    :param encoded_data: The base32 encoded data.
    :type encoded_data: str
    :param always_upper: If we should convert lowercase to uppercase
    :type always_upper: bool
    :return: hex-encoded payload
    :rtype: str
    """
    # First, add the padding to have a multiple of 8 bytes
    if always_upper:
        encoded_data = encoded_data.upper()
    encoded_length = len(encoded_data)
    if encoded_length % 8 != 0:
        encoded_data += "=" * (8 - (encoded_length % 8))
    assert len(encoded_data) % 8 == 0
    # Decode as base32
    try:
        decoded_data = base64.b32decode(encoded_data)
    except (TypeError, binascii.Error, OverflowError):
        # Python 3.6.7: b32decode throws a binascii.Error when the padding is wrong
        # Python 3.6.3 (travis): b32decode throws an OverflowError when the padding is wrong
        raise ParameterError("Malformed base32check data: Invalid base32")
    # Extract checksum and payload
    if len(decoded_data) < 4:
        raise ParameterError("Malformed base32check data: Too short")
    checksum, payload = decoded_data[:4], decoded_data[4:]
    payload_hash = hashlib.sha1(payload).digest()
    if payload_hash[:4] != checksum:
        raise ParameterError("Malformed base32check data: Incorrect checksum")
    return hexlify_and_unicode(payload) 
Example 27
Project: nano-python   Author: dourvaris   File: crypto.py    License: MIT License 5 votes vote down vote up
def b32xrb_decode(value):
    """
    Decodes a value in xrb encoding to bytes using base32 algorithm
    with a custom alphabet: '13456789abcdefghijkmnopqrstuwxyz'

    :param value: the value to decode
    :type: bytes

    :return: decoded value
    :rtype: bytes

    >>> b32xrb_decode(b'fxop4ya=')
    b'okay'
    """
    return b32decode(value.translate(XRB_DECODE_TRANS)) 
Example 28
Project: guacapy   Author: pschmitt   File: client.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_hotp_token(secret, intervals_no):
    key = base64.b32decode(secret, True)
    msg = struct.pack(">Q", intervals_no)
    h = bytes(hmac.new(key, msg, hashlib.sha1).digest())
    o = h[19] & 15
    h = (struct.unpack(">I", h[o : o + 4])[0] & 0x7FFFFFFF) % 1000000
    return h 
Example 29
Project: BinderFilter   Author: dxwu   File: test_base64.py    License: MIT License 5 votes vote down vote up
def test_b32decode(self):
        eq = self.assertEqual
        eq(base64.b32decode(''), '')
        eq(base64.b32decode('AA======'), '\x00')
        eq(base64.b32decode('ME======'), 'a')
        eq(base64.b32decode('MFRA===='), 'ab')
        eq(base64.b32decode('MFRGG==='), 'abc')
        eq(base64.b32decode('MFRGGZA='), 'abcd')
        eq(base64.b32decode('MFRGGZDF'), 'abcde')
        # Non-bytes
        self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG===')) 
Example 30
Project: BinderFilter   Author: dxwu   File: test_base64.py    License: MIT License 5 votes vote down vote up
def test_b32decode_error(self):
        self.assertRaises(TypeError, base64.b32decode, 'abc')
        self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==')