Python base64.encodebytes() Examples

The following are 30 code examples of base64.encodebytes(). 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: __init__.py    From jgscm with 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 #2
Source File: api.py    From insightconnect-plugins with 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 #3
Source File: helpers.py    From pytos with 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 #4
Source File: client.py    From misp42splunk with 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 #5
Source File: animation.py    From python3_ios with 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 #6
Source File: abstract_storage.py    From cassandra-medusa with 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 #7
Source File: client.py    From deepWordBug with 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 #8
Source File: client.py    From misp42splunk with 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 #9
Source File: image.py    From ParlAI with 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 #10
Source File: animation.py    From GraphicDesignPatternByPython with 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 #11
Source File: _http.py    From deepWordBug with 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 #12
Source File: _http.py    From vnpy_crypto with 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 #13
Source File: client.py    From verge3d-blender-addon with 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 #14
Source File: client.py    From kgsgo-dataset-preprocessor with 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 #15
Source File: test_base64.py    From Fluid-Designer with 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
Source File: representer.py    From pipenv with MIT License 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 #17
Source File: base64_codec.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def encode(self, input, final=False):
        assert self.errors == 'strict'
        return base64.encodebytes(input) 
Example #18
Source File: community.py    From py-ipv8 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def request_attestation(self, peer, attribute_name, secret_key, metadata={}):
        """
        Request attestation of one of our attributes.

        :param peer: Peer of the Attestor
        :param attribute_name: the attribute we want attested
        :param secret_key: the secret key we use for this attribute
        """
        public_key = secret_key.public_key()
        id_format = metadata.pop("id_format", "id_metadata")

        meta_dict = {
            "attribute": attribute_name,
            "public_key": cast_to_chr(encodebytes(public_key.serialize())),
            "id_format": id_format
        }
        meta_dict.update(metadata)
        metadata = json.dumps(meta_dict).encode()

        global_time = self.claim_global_time()
        auth = BinMemberAuthenticationPayload(self.my_peer.public_key.key_to_bin()).to_pack_list()
        payload = RequestAttestationPayload(metadata).to_pack_list()
        dist = GlobalTimeDistributionPayload(global_time).to_pack_list()

        gtime_str = str(global_time).encode('utf-8')
        self.request_cache.add(ReceiveAttestationRequestCache(self, peer.mid + gtime_str, secret_key, attribute_name,
                                                              id_format))
        self.allowed_attestations[peer.mid] = (self.allowed_attestations.get(peer.mid, [])
                                               + [gtime_str])

        packet = self._ez_pack(self._prefix, 5, [auth, dist, payload])
        self.endpoint.send(peer.address, packet) 
Example #19
Source File: AliPay.py    From django-RESTfulAPI with MIT License 5 votes vote down vote up
def sign(self, unsigned_string):
        # 开始计算签名
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(SHA256.new(unsigned_string))
        # base64 编码,转换为unicode表示并移除回车
        sign = encodebytes(signature).decode("utf8").replace("\n", "")
        return sign 
Example #20
Source File: encoders.py    From Fluid-Designer with 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(decode=True)
    encdata = str(_bencode(orig), 'ascii')
    msg.set_payload(encdata)
    msg['Content-Transfer-Encoding'] = 'base64' 
Example #21
Source File: base64_codec.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def base64_encode(input, errors='strict'):
    assert errors == 'strict'
    return (base64.encodebytes(input), len(input)) 
Example #22
Source File: base64_codec.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def base64_encode(input, errors='strict'):
    assert errors == 'strict'
    return (base64.encodebytes(input), len(input)) 
Example #23
Source File: QATTSBroker.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def encrypt(self, source_obj):
        encrypter = self._cipher.encryptor()
        source = json.dumps(source_obj)
        source = source.encode(self._encoding)
        need_to_padding = 16 - (len(source) % 16)
        if need_to_padding > 0:
            source = source + b'\x00' * need_to_padding
        enc_data = encrypter.update(source) + encrypter.finalize()
        b64_enc_data = base64.encodebytes(enc_data)
        return urllib.parse.quote(b64_enc_data) 
Example #24
Source File: auth_service.py    From consuming_services_python_demos with MIT License 5 votes vote down vote up
def check_user_and_password(auth_val):
    user = b'kennedy'
    pw = b'super_lockdown'

    expected_bytes = base64.encodebytes(user + b':' + pw)
    expected = expected_bytes.decode('utf-8').strip()

    return auth_val == expected 
Example #25
Source File: signer.py    From galaxy-fds-sdk-python with Apache License 2.0 5 votes vote down vote up
def _sign_to_base64(self, method, headers, url, app_secret):
    '''
    Sign the specified request to base64 encoded result.
    :param method:     The request method to sign
    :param headers:    The request headers to sign
    :param url:        The request uri to sign
    :param app_secret: The secret used to sign the request
    :return: The signed result, aka the signature
    '''
    signature = self._sign(method, headers, url, app_secret)
    if IS_PY3:
      return base64.encodebytes(signature).decode(encoding='utf-8').strip()
    else:
      return base64.encodestring(signature).strip() 
Example #26
Source File: client.py    From deepWordBug with Apache License 2.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 #27
Source File: encoders.py    From deepWordBug with Apache License 2.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 #28
Source File: _handshake.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def _create_sec_websocket_key():
    randomness = os.urandom(16)
    return base64encode(randomness).decode('utf-8').strip() 
Example #29
Source File: _handshake.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def _validate(headers, key, subprotocols):
    subproto = None
    for k, v in _HEADERS_TO_CHECK.items():
        r = headers.get(k, None)
        if not r:
            return False, None
        r = r.lower()
        if v != r:
            return False, None

    if subprotocols:
        subproto = headers.get("sec-websocket-protocol", None).lower()
        if not subproto or subproto not in [s.lower() for s in subprotocols]:
            error("Invalid subprotocol: " + str(subprotocols))
            return False, None

    result = headers.get("sec-websocket-accept", None)
    if not result:
        return False, None
    result = result.lower()

    if isinstance(result, six.text_type):
        result = result.encode('utf-8')

    value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
    hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
    success = compare_digest(hashed, result)

    if success:
        return True, subproto
    else:
        return False, None 
Example #30
Source File: representer.py    From deepWordBug with Apache License 2.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='|')