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


Python base64.b32encode方法代码示例

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


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

示例1: get_id

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def get_id(source_uuid):
    """Derive a short (12 character) id from a random UUID.

    The supplied UUID must be a version 4 UUID object.
    """

    if isinstance(source_uuid, str):
        source_uuid = uuid.UUID(source_uuid)
    if source_uuid.version != 4:
        raise ValueError(_('Invalid UUID version (%d)') % source_uuid.version)

    # The "time" field of a v4 UUID contains 60 random bits
    # (see RFC4122, Section 4.4)
    random_bytes = _to_byte_string(source_uuid.time, 60)
    # The first 12 bytes (= 60 bits) of base32-encoded output is our data
    encoded = base64.b32encode(random_bytes.encode("latin-1"))[:12]

    return encoded.lower().decode('utf-8') 
开发者ID:openstack,项目名称:zun,代码行数:20,代码来源:short_id.py

示例2: from_torrent_url

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def from_torrent_url(url):
    import base64
    import bencode
    import hashlib
    import urllib
    from kmediatorrent.utils import url_get
    torrent_data = url_get(url)
    metadata = bencode.bdecode(torrent_data)
    hashcontents = bencode.bencode(metadata['info'])
    digest = hashlib.sha1(hashcontents).digest()
    b32hash = base64.b32encode(digest)
    params = {
        'dn': metadata['info']['name'],
        'tr': metadata['announce'],
    }
    plugin.log.info(params)
    paramstr = urllib.urlencode(params)
    return 'magnet:?%s&%s' % ('xt=urn:btih:%s' % b32hash, paramstr) 
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:20,代码来源:magnet.py

示例3: totpauth_url

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def totpauth_url(totp_dev):
    # https://github.com/google/google-authenticator/wiki/Key-Uri-Format
    label = totp_dev.user.username.encode('utf8')

    # We need two separate issuers, otherwise deploying in prod will override our authenticator token from
    # dev
    if settings.DEPLOY_MODE == 'production':
        issuer = b'CourSys'
    else:
        issuer = b'CourSys-DEV'

    query = [
        ('secret', base64.b32encode(totp_dev.bin_key)),
        ('digits', totp_dev.digits),
        ('issuer', issuer)
    ]
    return b'otpauth://totp/%s?%s' % (label, urlencode(query).encode('ascii'))


# based on http://stackoverflow.com/a/4631504/1236542 
开发者ID:sfu-fas,项目名称:coursys,代码行数:22,代码来源:models.py

示例4: _to_safe_path_param_name

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def _to_safe_path_param_name(matched_parameter):
    """Creates a safe string to be used as a regex group name.

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

    We cast the matched_parameter to base32 (since the alphabet is safe),
    strip the padding (= not safe) and prepend with _, since we know a token
    can begin with underscore.

    Args:
      matched_parameter: A string containing the parameter matched from the URL
        template.

    Returns:
      A string that's safe to be used as a regex group name.
    """
    return '_' + base64.b32encode(matched_parameter).rstrip('=') 
开发者ID:elsigh,项目名称:browserscope,代码行数:20,代码来源:api_config_manager.py

示例5: _ToSafePathParamName

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def _ToSafePathParamName(matched_parameter):
    """Creates a safe string to be used as a regex group name.

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

    We cast the matched_parameter to base32 (since the alphabet is safe),
    strip the padding (= not safe) and prepend with _, since we know a token
    can begin with underscore.

    Args:
      matched_parameter: String; parameter matched from URL template.

    Returns:
      String, safe to be used as a regex group name.
    """
    return '_' + base64.b32encode(matched_parameter).rstrip('=') 
开发者ID:elsigh,项目名称:browserscope,代码行数:19,代码来源:dev_appserver_apiserver.py

示例6: address_from_identity_key

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def address_from_identity_key(key: Union[bytes, 'cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey', 'cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey'], suffix: bool = True) -> str:  # type: ignore
    """
    Converts a hidden service identity key into its address. This accepts all
    key formats (private, public, or public bytes).

    :param key: hidden service identity key
    :param suffix: includes the '.onion' suffix if true, excluded otherwise

    :returns: **str** hidden service address

    :raises: **ImportError** if key is a cryptographic type and ed25519 support
      is unavailable
    """

    key = stem.util._pubkey_bytes(key)  # normalize key into bytes

    version = stem.client.datatype.Size.CHAR.pack(3)
    checksum = hashlib.sha3_256(CHECKSUM_CONSTANT + key + version).digest()[:2]
    onion_address = base64.b32encode(key + checksum + version)

    return stem.util.str_tools._to_unicode(onion_address + b'.onion' if suffix else onion_address).lower() 
开发者ID:torproject,项目名称:stem,代码行数:23,代码来源:hidden_service.py

示例7: _filter_encode

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def _filter_encode(self, data, encoding):
		if its.py_v3 and isinstance(data, str):
			data = data.encode('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.b16encode(data)
		elif encoding == 'base32':
			data = base64.b32encode(data)
		elif encoding == 'base64':
			data = base64.b64encode(data)
		elif encoding == 'rot13':
			data = codecs.getencoder('rot-13')(data.decode('utf-8'))[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

示例8: connect

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def connect(self):
    if not self.trade_pub_socket and self.trade_pub:
      self.trade_pub_socket = self.zmq_context.socket(zmq.SUB)
      self.trade_pub_socket.connect(self.trade_pub)
      self.trade_pub_socket_stream = ZMQStream(self.trade_pub_socket)
      self.trade_pub_socket_stream.on_recv(self._on_trade_publish)

    self.trade_in_socket.send( "OPN," + base64.b32encode(os.urandom(10)))
    response_message = self.trade_in_socket.recv()
    opt_code    = response_message[:3]
    raw_message = response_message[4:]

    if opt_code != 'OPN':
      if opt_code == 'ERR':
        raise TradeClientException( error_message = raw_message )

      raise TradeClientException( error_message = 'Protocol Error: Unknown message opt_code received' )

    self.connection_id = raw_message 
开发者ID:bitex-coin,项目名称:backend,代码行数:21,代码来源:zmq_client.py

示例9: crypter

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def crypter(ack='',iv='2769514380123456',base='b64'):
    ahk = hmac.new(b'vilame',ack.encode(),'md5').hexdigest()
    c = CrypterAES(ahk, iv)
    if base == 'b16': _encode,_decode = base64.b16encode,base64.b16decode
    if base == 'b32': _encode,_decode = base64.b32encode,base64.b32decode
    if base == 'b64': _encode,_decode = base64.b64encode,base64.b64decode
    if base == 'b85': _encode,_decode = base64.b85encode,base64.b85decode
    if base == 'urlsafe_b64': _encode,_decode = base64.urlsafe_b64encode,base64.urlsafe_b64decode
    def zbase_enc(data):
        return _encode(zlib.compress(data.encode())[2:-4]).decode()
    def zbase_dec(basedata):
        return zlib.decompress(_decode(basedata),-15).decode()
    def zencrypt(data): return c.encrypt_base(zlib.compress(data.encode())[2:-4],_encode)
    def zdecrypt(data): return zlib.decompress(c.decrypt_base(data,_decode),-15).decode()
    c.zencrypt = zencrypt
    c.zdecrypt = zdecrypt
    c.zbase_enc = zbase_enc
    c.zbase_dec = zbase_dec
    c.encrypt = lambda data:c.encrypt_base(data,_encode)
    c.decrypt = lambda data:c.decrypt_base(data,_decode).decode()
    return c 
开发者ID:cilame,项目名称:vrequest,代码行数:23,代码来源:pyzlibaes.py

示例10: _generate_uri

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def _generate_uri(hotp, type_name, account_name, issuer, extra_parameters):
    parameters = [
        ("digits", hotp._length),
        ("secret", base64.b32encode(hotp._key)),
        ("algorithm", hotp._algorithm.name.upper()),
    ]

    if issuer is not None:
        parameters.append(("issuer", issuer))

    parameters.extend(extra_parameters)

    uriparts = {
        "type": type_name,
        "label": ("%s:%s" % (quote(issuer), quote(account_name)) if issuer
                  else quote(account_name)),
        "parameters": urlencode(parameters),
    }
    return "otpauth://{type}/{label}?{parameters}".format(**uriparts) 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:21,代码来源:utils.py

示例11: writeServerPassword

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def writeServerPassword( password ):
    """
    Dump our ScrambleSuit server descriptor to file.

    The file should make it easy for bridge operators to obtain copy &
    pasteable server descriptors.
    """

    assert len(password) == const.SHARED_SECRET_LENGTH
    assert const.STATE_LOCATION != ""

    passwordFile = os.path.join(const.STATE_LOCATION, const.PASSWORD_FILE)
    log.info("Writing server password to file `%s'." % passwordFile)

    password_str = "# You are supposed to give this password to your clients to append it to their Bridge line"
    password_str = "# For example: Bridge scramblesuit 192.0.2.1:5555 EXAMPLEFINGERPRINTNOTREAL password=EXAMPLEPASSWORDNOTREAL"
    password_str = "# Here is your password:"
    password_str = "password=%s\n" % base64.b32encode(password)
    try:
        with open(passwordFile, 'w') as fd:
            fd.write(password_str)
    except IOError as err:
        log.error("Error writing password file to `%s': %s" %
                  (passwordFile, err)) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:26,代码来源:state.py

示例12: get_public_server_options

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def get_public_server_options( cls, transportOptions ):
        """
        Return ScrambleSuit's BridgeDB parameters, i.e., the shared secret.

        As a fallback mechanism, we return an automatically generated password
        if the bridge operator did not use `ServerTransportOptions'.
        """

        log.debug("Tor's transport options: %s" % str(transportOptions))

        if not "password" in transportOptions:
            log.warning("No password found in transport options (use Tor's " \
                        "`ServerTransportOptions' to set your own password)." \
                        "  Using automatically generated password instead.")
            srv = state.load()
            transportOptions = {"password":
                                base64.b32encode(srv.fallbackPassword)}
            cls.uniformDHSecret = srv.fallbackPassword

        return transportOptions 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:22,代码来源:scramblesuit.py

示例13: __init__

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def __init__(self):
        self.nodes = []

        self.metadata = self.config.get('metadata', {})
        try:
            creator = self.metadata['creator']
        except KeyError:
            raise UsageError("Must specify creator metadata.")

        if not creator.isalnum():
            raise UsageError(
                "Creator must be alphanumeric. Found {!r}".format(creator)
            )
        self.creator = creator

        self.metadata.update(self.identity.metadata)
        self.metadata['distribution'] = self.distribution

        # Try to make names unique even if the same creator is starting
        # multiple clusters at the same time.  This lets other code use the
        # name as a way to identify nodes.  This is only necessary in one
        # place, the node creation code, to perform cleanup when the create
        # operation fails in a way such that it isn't clear if the instance has
        # been created or not.
        self.random_tag = b32encode(os.urandom(8)).lower().strip("\n=") 
开发者ID:ClusterHQ,项目名称:flocker,代码行数:27,代码来源:acceptance.py

示例14: base32_encode

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [as 别名]
def base32_encode(self):
        """Encode as Base32
        
        Base32 is a notation for encoding arbitrary byte data using a 
        restricted set of symbols that can be conveniently used by humans 
        and processed by computers. It uses a smaller set of characters than 
        Base64, usually the uppercase alphabet and the numbers 2 to 7.
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> Chepy("some data").base32_encode().output.decode()
            "ONXW2ZJAMRQXIYI="
        """
        self.state = base64.b32encode(self._convert_to_bytes())
        return self 
开发者ID:securisec,项目名称:chepy,代码行数:19,代码来源:dataformat.py

示例15: reroot_tree

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b32encode [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


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