当前位置: 首页>>代码示例>>Python>>正文


Python base64.b32decode方法代码示例

本文整理汇总了Python中base64.b32decode方法的典型用法代码示例。如果您正苦于以下问题:Python base64.b32decode方法的具体用法?Python base64.b32decode怎么用?Python base64.b32decode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在base64的用法示例。


在下文中一共展示了base64.b32decode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _from_safe_path_param_name

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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) 
开发者ID:elsigh,项目名称:browserscope,代码行数:22,代码来源:api_config_manager.py

示例2: _FromSafePathParamName

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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) 
开发者ID:elsigh,项目名称:browserscope,代码行数:22,代码来源:dev_appserver_apiserver.py

示例3: _filter_decode

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:21,代码来源:templates.py

示例4: torrent

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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 
开发者ID:rndusr,项目名称:torf,代码行数:23,代码来源:_magnet.py

示例5: test_b32decode_casefold

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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') 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:22,代码来源:test_base64.py

示例6: generate_token

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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 
开发者ID:awslabs,项目名称:aws-security-automation,代码行数:22,代码来源:ForceUserMFA.py

示例7: test_b32decode

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:18,代码来源:test_base64.py

示例8: reroot_tree

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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}) 
开发者ID:merenlab,项目名称:anvio,代码行数:24,代码来源:bottleroutes.py

示例9: read_qa_comat

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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 
开发者ID:yangliuy,项目名称:NeuralResponseRanking,代码行数:19,代码来源:rank_io.py

示例10: generate_code

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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
#---------------------------------------------------------------------- 
开发者ID:skywind3000,项目名称:collection,代码行数:24,代码来源:googauth.py

示例11: read_qrcode

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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 
开发者ID:seiferteric,项目名称:qrtun,代码行数:22,代码来源:qrtun_async.py

示例12: decode_qr_code_data

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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") 
开发者ID:unchained-capital,项目名称:hermit,代码行数:20,代码来源:format.py

示例13: decode

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
def decode(self, text):
		if len(text) % 8:
			text += "="*(8-(len(text)%8))
		try:
			return base64.b32decode(text.upper())
		except:
			return "" 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:9,代码来源:encoding.py

示例14: partial_split_qr_decode

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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 
开发者ID:ricmoo,项目名称:pycoind,代码行数:31,代码来源:piecewise.py

示例15: identity_key_from_address

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32decode [as 别名]
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 
开发者ID:torproject,项目名称:stem,代码行数:37,代码来源:hidden_service.py


注:本文中的base64.b32decode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。