Python base64.b32encode() Examples

The following are 30 code examples of base64.b32encode(). 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 also want to check out all available functions/classes of the module base64 , or try the search function .
Example #1
Source File: zmq_client.py    From backend with 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 #2
Source File: api_config_manager.py    From endpoints-python with 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 #3
Source File: hidden_service.py    From stem with 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 #4
Source File: utils.py    From teleport with 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 #5
Source File: dev_appserver_apiserver.py    From browserscope with 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
Source File: api_config_manager.py    From browserscope with 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
Source File: hiddenservice.py    From torpy with 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 #8
Source File: NSEC3.py    From luscan-devel with 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 #9
Source File: models.py    From coursys with 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 #10
Source File: utils.py    From teleport with 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 #11
Source File: magnet.py    From plugin.video.kmediatorrent with 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 #12
Source File: short_id.py    From zun with 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 #13
Source File: utils.py    From teleport with 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 #14
Source File: templates.py    From king-phisher with 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 #15
Source File: acceptance.py    From flocker with 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 #16
Source File: pyzlibaes.py    From vrequest with 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 #17
Source File: utils.py    From oss-ftp with 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 #18
Source File: state.py    From Safejumper-for-Desktop with 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 #19
Source File: utils.py    From learn_python3_spider with 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 #20
Source File: scramblesuit.py    From Safejumper-for-Desktop with 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 #21
Source File: dataformat.py    From chepy with 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
Source File: bottleroutes.py    From anvio with 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
Source File: NSEC3.py    From script.elementum.burst with 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
Source File: path_regex.py    From endpoints-management-python with 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 #25
Source File: utils.py    From Safejumper-for-Desktop with 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 #26
Source File: short_id.py    From magnum with 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 #27
Source File: decrypt_otpauth.py    From decrypt-otpauth-files with MIT License 5 votes vote down vote up
def otp_uri(self):
        otp_type = self.type.uri_value
        otp_label = quote(f'{self.issuer}:{self.label}')
        otp_parameters = {
            'secret': base64.b32encode(self.secret).decode("utf-8").rstrip("="),
            'algorithm': self.algorithm.uri_value,
            'period': self.period,
            'digits': self.digits,
            'issuer': self.issuer,
            'counter': self.counter,
        }
        otp_parameters = '&'.join([f'{str(k)}={quote(str(v))}' for (k, v) in otp_parameters.items() if v])
        return f'otpauth://{otp_type}/{otp_label}?{otp_parameters}' 
Example #28
Source File: test_TransferTransactionBuilder.py    From catbuffer-generators with MIT License 5 votes vote down vote up
def test_recipient_address(self):
            recipientAddress = base64.b32encode(
                bytes.fromhex(self.builder.getRecipientAddress().unresolvedAddress.hex()))
            self.assertEqual(recipientAddress, self.recipientAddress) 
Example #29
Source File: orm.py    From nativeauthenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, **kwargs):
        super(UserInfo, self).__init__(**kwargs)
        if not self.otp_secret:
            self.otp_secret = base64.b32encode(os.urandom(10)).decode('utf-8') 
Example #30
Source File: digestverifyingreader.py    From warcio with Apache License 2.0 5 votes vote down vote up
def _to_b32(length, value):
    '''
    Convert value to base 32, given that it's supposed to have the same
    length as the digest we're about to compare it to
    '''
    if len(value) == length:
        return value  # casefold needed here? -- rfc recommends not allowing

    if len(value) > length:
        binary = base64.b16decode(value, casefold=True)
    else:
        binary = _b64_wrapper(value)

    return to_native_str(base64.b32encode(binary), encoding='ascii')