Python base64.encodebytes() Examples

The following are 30 code examples for showing how to use base64.encodebytes(). 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: verge3d-blender-addon   Author: Soft8Soft   File: client.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_host_info(self, host):

        x509 = {}
        if isinstance(host, tuple):
            host, x509 = host

        auth, host = urllib_parse.splituser(host)

        if auth:
            auth = urllib_parse.unquote_to_bytes(auth)
            auth = base64.encodebytes(auth).decode("utf-8")
            auth = "".join(auth.split()) # get rid of whitespace
            extra_headers = [
                ("Authorization", "Basic " + auth)
                ]
        else:
            extra_headers = []

        return host, extra_headers, x509

    ##
    # Connect to server.
    #
    # @param host Target host.
    # @return An HTTPConnection object 
Example 2
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_host_info(self, host):

        x509 = {}
        if isinstance(host, tuple):
            host, x509 = host

        auth, host = urllib_parse.splituser(host)

        if auth:
            auth = urllib_parse.unquote_to_bytes(auth)
            auth = base64.encodebytes(auth).decode("utf-8")
            auth = "".join(auth.split()) # get rid of whitespace
            extra_headers = [
                ("Authorization", "Basic " + auth)
                ]
        else:
            extra_headers = []

        return host, extra_headers, x509

    ##
    # Connect to server.
    #
    # @param host Target host.
    # @return An HTTPConnection object 
Example 3
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_host_info(self, host):

        x509 = {}
        if isinstance(host, tuple):
            host, x509 = host

        auth, host = urllib_parse.splituser(host)

        if auth:
            auth = urllib_parse.unquote_to_bytes(auth)
            auth = base64.encodebytes(auth).decode("utf-8")
            auth = "".join(auth.split()) # get rid of whitespace
            extra_headers = [
                ("Authorization", "Basic " + auth)
                ]
        else:
            extra_headers = []

        return host, extra_headers, x509

    ##
    # Connect to server.
    #
    # @param host Target host.
    # @return An HTTPConnection object 
Example 4
Project: insightconnect-plugins   Author: rapid7   File: api.py    License: MIT License 6 votes vote down vote up
def _get_login_headers(self):
        session_response = self.mc_afee_request.make_json_request("POST", "session.php", headers={
            "Accept": "application/vnd.ve.v1.0+json",
            "Content-Type": "application/json",
            "VE-SDK-API": base64.encodebytes(
                f"{self.username}:{self.password}".encode()
            ).decode("utf-8").rstrip()
        })

        if session_response.get("success", False):
            session = session_response.get("results", {}).get("session")
            user_id = session_response.get("results", {}).get("userId")
            return {
                "Accept": "application/vnd.ve.v1.0+json",
                "VE-SDK-API": base64.encodebytes(
                    f"{session}:{user_id}".encode()
                ).decode("utf-8").rstrip()
            }

        raise ConnectionTestException(ConnectionTestException.Preset.USERNAME_PASSWORD) 
Example 5
Project: jgscm   Author: src-d   File: __init__.py    License: MIT License 6 votes vote down vote up
def _read_file(self, blob, format):
        """Reads a non-notebook file.

        blob: instance of :class:`google.cloud.storage.Blob`.
        format:
          If "text", the contents will be decoded as UTF-8.
          If "base64", the raw bytes contents will be encoded as base64.
          If not specified, try to decode as UTF-8, and fall back to base64
        """
        bcontent = blob.download_as_string()

        if format is None or format == "text":
            # Try to interpret as unicode if format is unknown or if unicode
            # was explicitly requested.
            try:
                return bcontent.decode("utf8"), "text"
            except UnicodeError:
                if format == "text":
                    raise web.HTTPError(
                        400, "%s is not UTF-8 encoded" %
                             self._get_blob_path(blob),
                        reason="bad format",
                    )
        return base64.encodebytes(bcontent).decode("ascii"), "base64" 
Example 6
Project: vnpy_crypto   Author: birforce   File: _http.py    License: MIT License 6 votes vote down vote up
def _tunnel(sock, host, port, auth):
    debug("Connecting proxy...")
    connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port)
    # TODO: support digest auth.
    if auth and auth[0]:
        auth_str = auth[0]
        if auth[1]:
            auth_str += ":" + auth[1]
        encoded_str = base64encode(auth_str.encode()).strip().decode()
        connect_header += "Proxy-Authorization: Basic %s\r\n" % encoded_str
    connect_header += "\r\n"
    dump("request header", connect_header)

    send(sock, connect_header)

    try:
        status, resp_headers, status_message = read_headers(sock)
    except Exception as e:
        raise WebSocketProxyException(str(e))

    if status != 200:
        raise WebSocketProxyException(
            "failed CONNECT via proxy status: %r" % status)

    return sock 
Example 7
Project: deepWordBug   Author: QData   File: _http.py    License: Apache License 2.0 6 votes vote down vote up
def _tunnel(sock, host, port, auth):
    debug("Connecting proxy...")
    connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port)
    # TODO: support digest auth.
    if auth and auth[0]:
        auth_str = auth[0]
        if auth[1]:
            auth_str += ":" + auth[1]
        encoded_str = base64encode(auth_str.encode()).strip().decode()
        connect_header += "Proxy-Authorization: Basic %s\r\n" % encoded_str
    connect_header += "\r\n"
    dump("request header", connect_header)

    send(sock, connect_header)

    try:
        status, resp_headers, status_message = read_headers(sock)
    except Exception as e:
        raise WebSocketProxyException(str(e))

    if status != 200:
        raise WebSocketProxyException(
            "failed CONNECT via proxy status: %r" % status)

    return sock 
Example 8
Project: deepWordBug   Author: QData   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def get_host_info(self, host):

        x509 = {}
        if isinstance(host, tuple):
            host, x509 = host

        auth, host = urllib_parse.splituser(host)

        if auth:
            auth = urllib_parse.unquote_to_bytes(auth)
            auth = base64.encodebytes(auth).decode("utf-8")
            auth = "".join(auth.split()) # get rid of whitespace
            extra_headers = [
                ("Authorization", "Basic " + auth)
                ]
        else:
            extra_headers = []

        return host, extra_headers, x509

    ##
    # Connect to server.
    #
    # @param host Target host.
    # @return An HTTPConnection object 
Example 9
Project: cassandra-medusa   Author: thelastpickle   File: abstract_storage.py    License: Apache License 2.0 6 votes vote down vote up
def generate_md5_hash(src, block_size=BLOCK_SIZE_BYTES):

        checksum = hashlib.md5()
        with open(str(src), 'rb') as f:
            # Incrementally read data and update the digest
            while True:
                read_data = f.read(block_size)
                if not read_data:
                    break
                checksum.update(read_data)

        # Once we have all the data, compute checksum
        checksum = checksum.digest()
        # Convert into a bytes type that can be base64 encoded
        base64_md5 = base64.encodebytes(checksum).decode('UTF-8').strip()
        # Print the Base64 encoded CRC32C
        return base64_md5 
Example 10
Project: kgsgo-dataset-preprocessor   Author: hughperkins   File: client.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def get_host_info(self, host):

        x509 = {}
        if isinstance(host, tuple):
            host, x509 = host

        auth, host = urllib_parse.splituser(host)

        if auth:
            auth = urllib_parse.unquote_to_bytes(auth)
            auth = base64.encodebytes(auth).decode("utf-8")
            auth = "".join(auth.split()) # get rid of whitespace
            extra_headers = [
                ("Authorization", "Basic " + auth)
                ]
        else:
            extra_headers = []

        return host, extra_headers, x509

    ##
    # Connect to server.
    #
    # @param host Target host.
    # @return An HTTPConnection object 
Example 11
Project: GraphicDesignPatternByPython   Author: Relph1119   File: animation.py    License: MIT License 6 votes vote down vote up
def grab_frame(self, **savefig_kwargs):
        if self.embed_frames:
            # Just stop processing if we hit the limit
            if self._hit_limit:
                return
            f = BytesIO()
            self.fig.savefig(f, format=self.frame_format,
                             dpi=self.dpi, **savefig_kwargs)
            imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
            self._total_bytes += len(imgdata64)
            if self._total_bytes >= self._bytes_limit:
                _log.warning(
                    "Animation size has reached %s bytes, exceeding the limit "
                    "of %s. If you're sure you want a larger animation "
                    "embedded, set the animation.embed_limit rc parameter to "
                    "a larger value (in MB). This and further frames will be "
                    "dropped.", self._total_bytes, self._bytes_limit)
                self._hit_limit = True
            else:
                self._saved_frames.append(imgdata64)
        else:
            return super().grab_frame(**savefig_kwargs) 
Example 12
Project: pytos   Author: Tufin   File: helpers.py    License: Apache License 2.0 6 votes vote down vote up
def get_topology_path_img(self, sources='0.0.0.0', destinations='0.0.0.0', services='ANY', url_params=None):
        """
        :param sources: comma separated list of source addresses e.g. 1.1.1.0:24
        :param destinations: comma separated list of destination addresses
        :param services: comma separated list of services
        :param url_params:
        :return: base64 string
        """
        logger.debug("sources={}, destinations={}, services={}, url_params={}".format(
             sources, destinations, services, url_params))
        if not url_params:
            url_params = ""
        else:
            param_builder = URLParamBuilderDict(url_params)
            url_params = param_builder.build(prepend_question_mark=False)

        src = ",".join(sources) if isinstance(sources, (list, tuple, set)) else sources
        dst = ",".join(destinations) if isinstance(destinations, (list, tuple, set)) else destinations
        srv = ",".join(services) if isinstance(services, (list, tuple, set)) else services
        uri = "/securetrack/api/topology/path_image?src={}&dst={}&service={}&{}".format(src, dst, srv, url_params)
        try:
            img = self.get_uri(uri, expected_status_codes=200).response.content
        except RequestException as error:
            raise IOError("Failed to securetrack configuration. Error: {}".format(error))
        return base64.encodebytes(img) 
Example 13
Project: python3_ios   Author: holzschu   File: animation.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def grab_frame(self, **savefig_kwargs):
        if self.embed_frames:
            # Just stop processing if we hit the limit
            if self._hit_limit:
                return
            f = BytesIO()
            self.fig.savefig(f, format=self.frame_format,
                             dpi=self.dpi, **savefig_kwargs)
            imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
            self._total_bytes += len(imgdata64)
            if self._total_bytes >= self._bytes_limit:
                _log.warning(
                    "Animation size has reached %s bytes, exceeding the limit "
                    "of %s. If you're sure you want a larger animation "
                    "embedded, set the animation.embed_limit rc parameter to "
                    "a larger value (in MB). This and further frames will be "
                    "dropped.", self._total_bytes, self._bytes_limit)
                self._hit_limit = True
            else:
                self._saved_frames.append(imgdata64)
        else:
            return super().grab_frame(**savefig_kwargs) 
Example 14
Project: ParlAI   Author: facebookresearch   File: image.py    License: MIT License 6 votes vote down vote up
def offload_state(self) -> Dict[str, str]:
        """
        Return serialized state.

        :return state_dict:
            serialized state that can be used in json.dumps
        """
        byte_arr = io.BytesIO()
        image = self.get_image()
        image.save(byte_arr, format="JPEG")
        serialized = base64.encodebytes(byte_arr.getvalue()).decode("utf-8")
        return {
            "image_id": self.get_image_id(),
            "image_location_id": self.get_image_location_id(),
            "image": serialized,
        } 
Example 15
Project: Fluid-Designer   Author: Microvellum   File: test_base64.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_encodebytes(self):
        eq = self.assertEqual
        eq(base64.encodebytes(b"www.python.org"), b"d3d3LnB5dGhvbi5vcmc=\n")
        eq(base64.encodebytes(b"a"), b"YQ==\n")
        eq(base64.encodebytes(b"ab"), b"YWI=\n")
        eq(base64.encodebytes(b"abc"), b"YWJj\n")
        eq(base64.encodebytes(b""), b"")
        eq(base64.encodebytes(b"abcdefghijklmnopqrstuvwxyz"
                               b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                               b"0123456789!@#0^&*();:<>,. []{}"),
           b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
           b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
           b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n")
        # Non-bytes
        eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\n')
        eq(base64.encodebytes(memoryview(b'abc')), b'YWJj\n')
        eq(base64.encodebytes(array('B', b'abc')), b'YWJj\n')
        self.check_type_errors(base64.encodebytes) 
Example 16
Project: pywren-ibm-cloud   Author: pywren   File: client.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, endpoint, namespace, api_key=None, auth=None, insecure=False, user_agent=None):
        """
        OpenWhiskClient Constructor

        :param endpoint: OpenWhisk endpoint.
        :param namespace: User namespace.
        :param api_key: User AUTH Key.  HTTP Basic authentication.
        :param auth: Authorization token string "Basic eyJraWQiOiIyMDE5MDcyNCIsImFsZ...".
        :param insecure: Insecure backend. Disable cert verification.
        :param user_agent: User agent on requests.
        """
        self.endpoint = endpoint.replace('http:', 'https:')
        self.namespace = namespace
        self.api_key = api_key
        self.auth = auth

        if self.api_key:
            api_key = str.encode(self.api_key)
            auth_token = base64.encodebytes(api_key).replace(b'\n', b'')
            self.auth = 'Basic %s' % auth_token.decode('UTF-8')

        self.session = requests.session()

        if insecure:
            self.session.verify = False

        self.headers = {
            'content-type': 'application/json',
            'Authorization': self.auth,
        }

        if user_agent:
            default_user_agent = self.session.headers['User-Agent']
            self.headers['User-Agent'] = default_user_agent + ' {}'.format(user_agent)

        self.session.headers.update(self.headers)
        adapter = requests.adapters.HTTPAdapter()
        self.session.mount('https://', adapter) 
Example 17
Project: verge3d-blender-addon   Author: Soft8Soft   File: encoders.py    License: GNU General Public License v3.0 5 votes vote down vote up
def encode_base64(msg):
    """Encode the message's payload in Base64.

    Also, add an appropriate Content-Transfer-Encoding header.
    """
    orig = msg.get_payload()
    encdata = str(_bencode(orig), 'ascii')
    msg.set_payload(encdata)
    msg['Content-Transfer-Encoding'] = 'base64' 
Example 18
Project: verge3d-blender-addon   Author: Soft8Soft   File: client.py    License: GNU General Public License v3.0 5 votes vote down vote up
def encode(self, out):
        out.write("<value><base64>\n")
        encoded = base64.encodebytes(self.data)
        out.write(encoded.decode('ascii'))
        out.write("</base64></value>\n") 
Example 19
Project: verge3d-blender-addon   Author: Soft8Soft   File: client.py    License: GNU General Public License v3.0 5 votes vote down vote up
def dump_bytes(self, value, write):
        write("<value><base64>\n")
        encoded = base64.encodebytes(value)
        write(encoded.decode('ascii'))
        write("</base64></value>\n") 
Example 20
Project: lavatory   Author: gogoair   File: artifactory.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, repo_name=None):
        self.repo_name = repo_name
        self.credentials = load_credentials()
        self.base_url = self.credentials['artifactory_url']
        self.artifactory = party.Party()
        if not self.base_url.endswith('/api'):
            self.api_url = '/'.join([self.base_url, 'api'])
        else:
            self.api_url = self.base_url
        self.artifactory.artifactory_url = self.api_url
        self.artifactory.username = self.credentials['artifactory_username']
        self.artifactory.password = base64.encodebytes(bytes(self.credentials['artifactory_password'], 'utf-8'))
        self.artifactory.certbundle = os.getenv('LAVATORY_CERTBUNDLE_PATH', certifi.where()) 
Example 21
Project: misp42splunk   Author: remg427   File: representer.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def represent_binary(self, data):
        if hasattr(base64, 'encodebytes'):
            data = base64.encodebytes(data).decode('ascii')
        else:
            data = base64.encodestring(data).decode('ascii')
        return self.represent_scalar('tag:yaml.org,2002:binary', data, style='|') 
Example 22
Project: misp42splunk   Author: remg427   File: encoders.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def encode_base64(msg):
    """Encode the message's payload in Base64.

    Also, add an appropriate Content-Transfer-Encoding header.
    """
    orig = msg.get_payload()
    encdata = str(_bencode(orig), 'ascii')
    msg.set_payload(encdata)
    msg['Content-Transfer-Encoding'] = 'base64' 
Example 23
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def encode(self, out):
        out.write("<value><base64>\n")
        encoded = base64.encodebytes(self.data)
        out.write(encoded.decode('ascii'))
        out.write("</base64></value>\n") 
Example 24
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def dump_bytes(self, value, write):
        write("<value><base64>\n")
        encoded = base64.encodebytes(value)
        write(encoded.decode('ascii'))
        write("</base64></value>\n") 
Example 25
Project: misp42splunk   Author: remg427   File: encoders.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def encode_base64(msg):
    """Encode the message's payload in Base64.

    Also, add an appropriate Content-Transfer-Encoding header.
    """
    orig = msg.get_payload()
    encdata = str(_bencode(orig), 'ascii')
    msg.set_payload(encdata)
    msg['Content-Transfer-Encoding'] = 'base64' 
Example 26
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def encode(self, out):
        out.write("<value><base64>\n")
        encoded = base64.encodebytes(self.data)
        out.write(encoded.decode('ascii'))
        out.write("</base64></value>\n") 
Example 27
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def dump_bytes(self, value, write):
        write("<value><base64>\n")
        encoded = base64.encodebytes(value)
        write(encoded.decode('ascii'))
        write("</base64></value>\n") 
Example 28
Project: R-A-M-D-D3-S-M-H   Author: inlike   File: RSA-AES-MD5-DES-DES3-MD5-SHA-HMAC.py    License: MIT License 5 votes vote down vote up
def encrypt(self, text):
        aes = self.aes()
        return str(base64.encodebytes(aes.encrypt(self.to_16(text))),
                   encoding='utf8').replace('\n', '')  # 加密 
Example 29
Project: jgscm   Author: src-d   File: test.py    License: MIT License 5 votes vote down vote up
def test_save_file(self):
        self.contents_manager.save({
            "type": "file",
            "content": "blah-blah-blah",
            "format": "text"
        }, self.path("test.txt"))
        bucket = self.bucket
        blob = bucket.blob("test.txt")
        self.assertTrue(blob.exists())
        try:
            self.assertEqual(blob.download_as_string(), b"blah-blah-blah")
        finally:
            blob.delete()

        obj = {"one": 1, "two": [2, 3]}
        self.contents_manager.save({
            "type": "file",
            "content": base64.encodebytes(pickle.dumps(obj)).decode("ascii"),
            "format": "base64"
        }, self.path("test.pickle"))
        bucket = self.bucket
        blob = bucket.blob("test.pickle")
        self.assertTrue(blob.exists())
        try:
            self.assertEqual(blob.download_as_string(), pickle.dumps(obj))
        finally:
            blob.delete() 
Example 30
Project: px   Author: genotrance   File: px.py    License: MIT License 5 votes vote down vote up
def b64encode(val):
    try:
        return base64.encodebytes(val.encode("utf-8"))
    except AttributeError:
        return base64.encodestring(val)