Python base64.b32encode() Examples

The following are 30 code examples for showing how to use base64.b32encode(). 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: zun   Author: openstack   File: short_id.py    License: Apache License 2.0 6 votes vote down vote up
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') 
Example 2
Project: plugin.video.kmediatorrent   Author: jmarth   File: magnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
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) 
Example 3
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 4
Project: browserscope   Author: elsigh   File: api_config_manager.py    License: Apache License 2.0 6 votes vote down vote up
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('=') 
Example 5
Project: browserscope   Author: elsigh   File: dev_appserver_apiserver.py    License: Apache License 2.0 6 votes vote down vote up
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('=') 
Example 6
Project: endpoints-python   Author: cloudendpoints   File: api_config_manager.py    License: Apache License 2.0 6 votes vote down vote up
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('=') 
Example 7
Project: stem   Author: torproject   File: hidden_service.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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() 
Example 8
Project: king-phisher   Author: rsmusllp   File: templates.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 9
Project: backend   Author: bitex-coin   File: zmq_client.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 
Example 10
Project: vrequest   Author: cilame   File: pyzlibaes.py    License: MIT License 6 votes vote down vote up
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 
Example 11
Project: oss-ftp   Author: aliyun   File: utils.py    License: MIT License 6 votes vote down vote up
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) 
Example 12
Project: Safejumper-for-Desktop   Author: proxysh   File: state.py    License: GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example 13
Project: Safejumper-for-Desktop   Author: proxysh   File: scramblesuit.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 
Example 14
Project: Safejumper-for-Desktop   Author: proxysh   File: utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 15
Project: teleport   Author: tp4a   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 16
Project: teleport   Author: tp4a   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 17
Project: teleport   Author: tp4a   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 18
Project: flocker   Author: ClusterHQ   File: acceptance.py    License: Apache License 2.0 6 votes vote down vote up
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=") 
Example 19
Project: endpoints-management-python   Author: cloudendpoints   File: path_regex.py    License: Apache License 2.0 6 votes vote down vote up
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('=') 
Example 20
Project: learn_python3_spider   Author: wistbean   File: utils.py    License: MIT License 6 votes vote down vote up
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) 
Example 21
Project: chepy   Author: securisec   File: dataformat.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 22
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 23
Project: script.elementum.burst   Author: elgatito   File: NSEC3.py    License: Do What The F*ck You Want To Public License 6 votes vote down vote up
def to_text(self, origin=None, relativize=True, **kw):
        next = base64.b32encode(self.next).translate(
            b32_normal_to_hex).lower().decode()
        if self.salt == b'':
            salt = '-'
        else:
            salt = binascii.hexlify(self.salt).decode()
        text = u''
        for (window, bitmap) in self.windows:
            bits = []
            for i in xrange(0, len(bitmap)):
                byte = bitmap[i]
                for j in xrange(0, 8):
                    if byte & (0x80 >> j):
                        bits.append(dns.rdatatype.to_text(window * 256 +
                                                          i * 8 + j))
            text += (u' ' + u' '.join(bits))
        return u'%u %u %u %s %s%s' % (self.algorithm, self.flags,
                                      self.iterations, salt, next, text) 
Example 24
Project: magnum   Author: openstack   File: short_id.py    License: Apache License 2.0 6 votes vote down vote up
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, six.string_types):
        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(six.b(random_bytes))[:12]

    if six.PY3:
        return encoded.lower().decode('utf-8')
    else:
        return encoded.lower() 
Example 25
Project: torpy   Author: torpyorg   File: hiddenservice.py    License: Apache License 2.0 6 votes vote down vote up
def _fetch_descriptor(self, descriptor_id):
        # tor ref: rend_client_fetch_v2_desc

        logger.info('Create circuit for hsdir')
        with self._circuit.create_new_circuit() as directory_circuit:
            directory_circuit.extend(self._router)
            assert directory_circuit.nodes_count == 2

            with directory_circuit.create_stream() as stream:
                stream.connect_dir()

                descriptor_id_str = b32encode(descriptor_id).decode().lower()

                # tor ref: directory_send_command (DIR_PURPOSE_FETCH_RENDDESC_V2)
                descriptor_path = '/tor/rendezvous2/{}'.format(descriptor_id_str)

                http_client = HttpClient(stream)
                response = http_client.get(self._router.ip, descriptor_path).decode()
                if response and ' 200 OK' in response:
                    return response
                else:
                    logger.error('Response from hsdir: %r', response)
                    raise DescriptorNotAvailable("Can't fetch descriptor") 
Example 26
Project: luscan-devel   Author: blackye   File: NSEC3.py    License: GNU General Public License v2.0 6 votes vote down vote up
def to_text(self, origin=None, relativize=True, **kw):
        next = base64.b32encode(self.next).translate(b32_normal_to_hex).lower()
        if self.salt == '':
            salt = '-'
        else:
            salt = self.salt.encode('hex-codec')
        text = ''
        for (window, bitmap) in self.windows:
            bits = []
            for i in xrange(0, len(bitmap)):
                byte = ord(bitmap[i])
                for j in xrange(0, 8):
                    if byte & (0x80 >> j):
                        bits.append(dns.rdatatype.to_text(window * 256 + \
                                                          i * 8 + j))
            text += (' ' + ' '.join(bits))
        return '%u %u %u %s %s%s' % (self.algorithm, self.flags, self.iterations,
                                     salt, next, text) 
Example 27
Project: XFLTReaT   Author: earthquake   File: encoding.py    License: MIT License 5 votes vote down vote up
def encode(self, text):
		return base64.b32encode(text).replace("=","").lower() 
Example 28
Project: pinnwand   Author: supakeen   File: utility.py    License: MIT License 5 votes vote down vote up
def hash_create(length: int = 16) -> str:
    return b32encode(urandom(length)).decode("ascii").replace("=", "") 
Example 29
Project: sato   Author: megagonlabs   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def long_name_digest(name, n = 10):
    return base64.b32encode(hashlib.sha1(name.encode()).digest()[:n]).decode("utf-8") 



# Iterator for reading large header file. 
Example 30
Project: backend.ai-manager   Author: lablup   File: keypair.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def generate_keypair() -> Tuple[AccessKey, SecretKey]:
    '''
    AWS-like access key and secret key generation.
    '''
    ak = 'AKIA' + base64.b32encode(secrets.token_bytes(10)).decode('ascii')
    sk = secrets.token_urlsafe(30)
    return AccessKey(ak), SecretKey(sk)