Python base64.standard_b64encode() Examples

The following are 30 code examples for showing how to use base64.standard_b64encode(). 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: warrant   Author: capless   File: aws_srp.py    License: Apache License 2.0 6 votes vote down vote up
def process_challenge(self, challenge_parameters):
        user_id_for_srp = challenge_parameters['USER_ID_FOR_SRP']
        salt_hex = challenge_parameters['SALT']
        srp_b_hex = challenge_parameters['SRP_B']
        secret_block_b64 = challenge_parameters['SECRET_BLOCK']
        # re strips leading zero from a day number (required by AWS Cognito)
        timestamp = re.sub(r" 0(\d) ", r" \1 ",
                           datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S UTC %Y"))
        hkdf = self.get_password_authentication_key(user_id_for_srp,
                                                    self.password, hex_to_long(srp_b_hex), salt_hex)
        secret_block_bytes = base64.standard_b64decode(secret_block_b64)
        msg = bytearray(self.pool_id.split('_')[1], 'utf-8') + bytearray(user_id_for_srp, 'utf-8') + \
              bytearray(secret_block_bytes) + bytearray(timestamp, 'utf-8')
        hmac_obj = hmac.new(hkdf, msg, digestmod=hashlib.sha256)
        signature_string = base64.standard_b64encode(hmac_obj.digest())
        response = {'TIMESTAMP': timestamp,
                    'USERNAME': user_id_for_srp,
                    'PASSWORD_CLAIM_SECRET_BLOCK': secret_block_b64,
                    'PASSWORD_CLAIM_SIGNATURE': signature_string.decode('utf-8')}
        if self.client_secret is not None:
            response.update({
                "SECRET_HASH":
                self.get_secret_hash(self.username, self.client_id, self.client_secret)})
        return response 
Example 2
Project: plugin.video.netflix   Author: CastagnaIT   File: android_crypto.py    License: MIT License 6 votes vote down vote up
def key_request_data(self):
        """Return a key request dict"""
        # No key update supported -> remove existing keys
        self.crypto_session.RemoveKeys()
        key_request = self.crypto_session.GetKeyRequest(  # pylint: disable=assignment-from-none
            bytearray([10, 122, 0, 108, 56, 43]), 'application/xml', True, dict())

        if not key_request:
            raise MSLError('Widevine CryptoSession getKeyRequest failed!')

        common.debug('Widevine CryptoSession getKeyRequest successful. Size: {}', len(key_request))

        # Save the key request (challenge data) required for manifest requests
        # Todo: to be implemented if/when it becomes mandatory
        key_request = base64.standard_b64encode(key_request).decode('utf-8')
        # g.LOCAL_DB.set_value('drm_session_challenge', key_request, TABLE_SESSION)

        return [{
            'scheme': 'WIDEVINE',
            'keydata': {
                'keyrequest': key_request
            }
        }] 
Example 3
Project: lightstep-tracer-python   Author: lightstep   File: lightstep_binary_propagator.py    License: MIT License 6 votes vote down vote up
def inject(self, span_context, carrier):
        if type(carrier) is not bytearray:
            raise InvalidCarrierException()

        state = BinaryCarrier()
        basic_ctx = state.basic_ctx

        basic_ctx.trace_id = span_context.trace_id
        basic_ctx.span_id = span_context.span_id
        basic_ctx.sampled = span_context.sampled
        if span_context.baggage is not None:
            for key in span_context.baggage:
                basic_ctx.baggage_items[key] = span_context.baggage[key]


        serializedProto = state.SerializeToString()
        encoded = standard_b64encode(serializedProto)
        carrier.extend(encoded) 
Example 4
Project: cos-python-sdk-v5   Author: tencentyun   File: cos_comm.py    License: MIT License 6 votes vote down vote up
def get_content_md5(body):
    """计算任何输入流的md5值"""
    if isinstance(body, text_type) or isinstance(body, binary_type):
        return get_md5(body)
    elif hasattr(body, 'tell') and hasattr(body, 'seek') and hasattr(body, 'read'):
        file_position = body.tell()  # 记录文件当前位置
        # avoid OOM
        md5 = hashlib.md5()
        chunk = body.read(DEFAULT_CHUNK_SIZE)
        while chunk:
            md5.update(to_bytes(chunk))
            chunk = body.read(DEFAULT_CHUNK_SIZE)
        md5_str = base64.standard_b64encode(md5.digest())
        try:
            body.seek(file_position)  # 恢复初始的文件位置
        except Exception as e:
            raise CosClientError('seek unsupported to calculate md5!')
        return md5_str
    else:
        raise CosClientError('unsupported body type to calculate md5!')
    return None 
Example 5
Project: Cloudroid   Author: cyberdb   File: message_conversion.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _from_inst(inst, rostype):
    # Special case for uint8[], we base64 encode the string
    if rostype in ros_binary_types:
        return standard_b64encode(inst)

    # Check for time or duration
    if rostype in ros_time_types:
        return {"secs": inst.secs, "nsecs": inst.nsecs}

    # Check for primitive types
    if rostype in ros_primitive_types:
        return inst

    # Check if it's a list or tuple
    if type(inst) in list_types:
        return _from_list_inst(inst, rostype)

    # Assume it's otherwise a full ros msg object
    return _from_object_inst(inst, rostype) 
Example 6
Project: dcos-kafka-service   Author: mesosphere   File: release_builder.py    License: Apache License 2.0 6 votes vote down vote up
def _update_marathon_json(self, package_json):
        """Updates the marathon.json definition to contain the desired name and version strings.
        """
        # note: the file isn't valid JSON, so we edit the raw content instead
        marathon_encoded = package_json.get("marathon", {}).get("v2AppMustacheTemplate")
        orig_marathon_lines = base64.standard_b64decode(marathon_encoded).decode().split("\n")

        marathon_lines = []
        for line in orig_marathon_lines:
            name_match = re.match(r'^ *"PACKAGE_NAME": ?"(.*)",?$', line.rstrip("\n"))
            version_match = re.match(r'^ *"PACKAGE_VERSION": ?"(.*)",?$', line.rstrip("\n"))
            if name_match:
                line = line.replace(name_match.group(1), self._pkg_name)
            elif version_match:
                line = line.replace(version_match.group(1), self._pkg_version)
            marathon_lines.append(line)

        log.info("Updated marathon.json.mustache:")
        log.info("\n".join(difflib.unified_diff(orig_marathon_lines, marathon_lines, lineterm="")))

        # Update parent package object with changes:
        package_json["marathon"]["v2AppMustacheTemplate"] = base64.standard_b64encode(
            "\n".join(marathon_lines).encode("utf-8")
        ).decode() 
Example 7
Project: Jandroid   Author: FSecureLABS   File: style_sheet_unittest.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testImages(self):
    fs = fake_fs.FakeFS()
    fs.AddFile('/src/foo/x.css', """
.x .y {
    background-image: url(../images/bar.jpeg);
}
""")
    fs.AddFile('/src/images/bar.jpeg', 'hello world')
    with fs:
      project = project_module.Project([os.path.normpath('/src/')])
      loader = resource_loader.ResourceLoader(project)

      foo_x = loader.LoadStyleSheet('foo.x')
      self.assertEquals(1, len(foo_x.images))

      r0 = foo_x.images[0]
      self.assertEquals(os.path.normpath('/src/images/bar.jpeg'),
                        r0.absolute_path)

      inlined = foo_x.contents_with_inlined_images
      self.assertEquals("""
.x .y {
    background-image: url(data:image/jpeg;base64,%s);
}
""" % base64.standard_b64encode('hello world'), inlined) 
Example 8
Project: Jandroid   Author: FSecureLABS   File: style_sheet.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def contents_with_inlined_images(self):
    images_by_url = {}
    for i in self.images:
      for a in i.aliases:
        images_by_url[a] = i

    def InlineUrl(m):
      url = m.group('url')
      image = images_by_url[url]

      ext = os.path.splitext(image.absolute_path)[1]
      data = base64.standard_b64encode(image.contents)

      return 'url(data:image/%s;base64,%s)' % (ext[1:], data)

    # I'm assuming we only have url()'s associated with images
    return re.sub('url\((?P<quote>"|\'|)(?P<url>[^"\'()]*)(?P=quote)\)',
                  InlineUrl, self.contents) 
Example 9
Project: Jandroid   Author: FSecureLABS   File: style_sheet_unittest.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testImages(self):
    fs = fake_fs.FakeFS()
    fs.AddFile('/src/foo/x.css', """
.x .y {
    background-image: url(../images/bar.jpeg);
}
""")
    fs.AddFile('/src/images/bar.jpeg', 'hello world')
    with fs:
      project = project_module.Project([os.path.normpath('/src/')])
      loader = resource_loader.ResourceLoader(project)

      foo_x = loader.LoadStyleSheet('foo.x')
      self.assertEquals(1, len(foo_x.images))

      r0 = foo_x.images[0]
      self.assertEquals(os.path.normpath('/src/images/bar.jpeg'),
                        r0.absolute_path)

      inlined = foo_x.contents_with_inlined_images
      self.assertEquals("""
.x .y {
    background-image: url(data:image/jpeg;base64,%s);
}
""" % base64.standard_b64encode('hello world'), inlined) 
Example 10
Project: Jandroid   Author: FSecureLABS   File: style_sheet.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def contents_with_inlined_images(self):
    images_by_url = {}
    for i in self.images:
      for a in i.aliases:
        images_by_url[a] = i

    def InlineUrl(m):
      url = m.group('url')
      image = images_by_url[url]

      ext = os.path.splitext(image.absolute_path)[1]
      data = base64.standard_b64encode(image.contents)

      return 'url(data:image/%s;base64,%s)' % (ext[1:], data)

    # I'm assuming we only have url()'s associated with images
    return re.sub('url\((?P<quote>"|\'|)(?P<url>[^"\'()]*)(?P=quote)\)',
                  InlineUrl, self.contents) 
Example 11
Project: Jandroid   Author: FSecureLABS   File: style_sheet_unittest.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testImages(self):
    fs = fake_fs.FakeFS()
    fs.AddFile('/src/foo/x.css', """
.x .y {
    background-image: url(../images/bar.jpeg);
}
""")
    fs.AddFile('/src/images/bar.jpeg', 'hello world')
    with fs:
      project = project_module.Project([os.path.normpath('/src/')])
      loader = resource_loader.ResourceLoader(project)

      foo_x = loader.LoadStyleSheet('foo.x')
      self.assertEquals(1, len(foo_x.images))

      r0 = foo_x.images[0]
      self.assertEquals(os.path.normpath('/src/images/bar.jpeg'),
                        r0.absolute_path)

      inlined = foo_x.contents_with_inlined_images
      self.assertEquals("""
.x .y {
    background-image: url(data:image/jpeg;base64,%s);
}
""" % base64.standard_b64encode('hello world'), inlined) 
Example 12
Project: MLOpsDatabricks   Author: Azure-Samples   File: cluster.py    License: MIT License 6 votes vote down vote up
def get_state(self, databricks_token):
        base_url = self.get_base_url()

        response = requests.post(
            base_url + 'clusters/get',
            headers={
                'Authorization': b"Basic " + base64.standard_b64encode(
                    b"token:" + str.encode(databricks_token))},
            json={
                "cluster_id": self.id
            })

        if response.status_code == 200:
            self.state = response.json()['state']
        else:
            raise ClusterManagementException(
                "Error getting cluster state: %s: %s" %
                (response.json()["error_code"], response.json()["message"])
            ) 
Example 13
Project: aqua-monitor   Author: Deltares   File: pem.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def save_pem(contents, pem_marker):
    """Saves a PEM file.

    :param contents: the contents to encode in PEM format
    :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
        when your file has '-----BEGIN RSA PRIVATE KEY-----' and
        '-----END RSA PRIVATE KEY-----' markers.

    :return: the base64-encoded content between the start and end markers.

    """

    (pem_start, pem_end) = _markers(pem_marker)

    b64 = base64.standard_b64encode(contents).replace(b('\n'), b(''))
    pem_lines = [pem_start]

    for block_start in range(0, len(b64), 64):
        block = b64[block_start:block_start + 64]
        pem_lines.append(block)

    pem_lines.append(pem_end)
    pem_lines.append(b(''))

    return b('\n').join(pem_lines) 
Example 14
Project: django-cloud-deploy   Author: GoogleCloudPlatform   File: container_test.py    License: Apache License 2.0 6 votes vote down vote up
def get(self, projectId, zone, clusterId):
        ca = base64.standard_b64encode(FAKE_CA).decode('utf-8')
        if 'invalid_response' in clusterId:
            return http_fake.HttpRequestFake(
                json.loads(CLUSTER_GET_RESPONSE_INVALID))
        if clusterId not in self.clusters_to_get_count:
            status = 'ERROR'
        else:
            self.clusters_to_get_count[clusterId][0] += 1
            get_count, total_get_count = self.clusters_to_get_count[clusterId]
            if get_count < total_get_count:
                status = 'PROVISIONING'
            else:
                status = 'RUNNING'
        response = CLUSTER_GET_RESPONSE_TEMPLATE.format(clusterId, ca, status)
        return http_fake.HttpRequestFake(json.loads(response)) 
Example 15
Project: jupyter-notebook-gist   Author: mozilla   File: handlers.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def get(self):

        # Extract access code
        access_code = extract_code_from_args(self.request.arguments)

        # Request access token from github
        access_token = self.request_access_token(access_code)

        github_headers = {"Accept": "application/json",
                          "Authorization": "token " + access_token}

        response = request_session.get("https://api.github.com/gists",
                                       headers=github_headers)
        response_to_send = bytearray(response.text, 'utf-8')
        self.write("<script>var gists = '")
        self.write(base64.standard_b64encode(response_to_send))
        self.write("';")
        self.write("window.opener.postMessage(gists, window.opener.location)")
        self.finish(";</script>") 
Example 16
Project: bash-lambda-layer   Author: gkrizek   File: pem.py    License: MIT License 6 votes vote down vote up
def save_pem(contents, pem_marker):
    """Saves a PEM file.

    :param contents: the contents to encode in PEM format
    :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
        when your file has '-----BEGIN RSA PRIVATE KEY-----' and
        '-----END RSA PRIVATE KEY-----' markers.

    :return: the base64-encoded content between the start and end markers.

    """

    (pem_start, pem_end) = _markers(pem_marker)

    b64 = base64.standard_b64encode(contents).replace(b('\n'), b(''))
    pem_lines = [pem_start]

    for block_start in range(0, len(b64), 64):
        block = b64[block_start:block_start + 64]
        pem_lines.append(block)

    pem_lines.append(pem_end)
    pem_lines.append(b(''))

    return b('\n').join(pem_lines) 
Example 17
Project: bitex   Author: Crypto-toolbox   File: bitfinex.py    License: MIT License 6 votes vote down vote up
def sign(self, url, endpoint, endpoint_path, method_verb, *args, **kwargs):
        try:
            req = kwargs['params']
        except KeyError:
            req = {}
        if self.version == 'v1':
            req['request'] = endpoint_path
            req['nonce'] = self.nonce()

            js = json.dumps(req)
            data = base64.standard_b64encode(js.encode('utf8'))
        else:
            data = '/api/' + endpoint_path + self.nonce() + json.dumps(req)
        h = hmac.new(self.secret.encode('utf8'), data, hashlib.sha384)
        signature = h.hexdigest()
        headers = {"X-BFX-APIKEY": self.key,
                   "X-BFX-SIGNATURE": signature,
                   "X-BFX-PAYLOAD": data}
        if self.version == 'v2':
            headers['content-type'] = 'application/json'

        return url, {'headers': headers} 
Example 18
Project: bitex   Author: Crypto-toolbox   File: gemini.py    License: MIT License 6 votes vote down vote up
def sign(self, uri, endpoint, endpoint_path, method_verb, *args, **kwargs):
        nonce = self.nonce()
        try:
            params = kwargs['params']
        except KeyError:
            params = {}
        payload = params
        payload['nonce'] = nonce
        payload['request'] = endpoint_path

        js = json.dumps(payload)
        data = base64.standard_b64encode(js.encode('utf8'))
        h = hmac.new(self.secret.encode('utf8'), data, hashlib.sha384)
        signature = h.hexdigest()
        headers = {'X-GEMINI-APIKEY': self.key,
                   'X-GEMINI-PAYLOAD': data,
                   'X-GEMINI-SIGNATURE': signature}
        return uri, {'headers': headers} 
Example 19
Project: nexus-exporter   Author: ocadotechnology   File: nexus_exporter.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, target, user, password):
        self._target = target.rstrip("/")
        auth_string = '%s:%s' % (user, password)
        self._auth = base64.standard_b64encode(auth_string.encode()).decode('utf8')
        self._info = {}
        self._data = {} 
Example 20
Project: pySmartDL   Author: iTaybb   File: pySmartDL.py    License: The Unlicense 5 votes vote down vote up
def add_basic_authentication(self, username, password):
        '''
        Uses HTTP Basic Access authentication for the connection.
        
        :param username: Username.
        :type username: string
        :param password: Password.
        :type password: string
        '''
        auth_string = '{}:{}'.format(username, password)
        base64string = base64.standard_b64encode(auth_string.encode('utf-8'))
        self.requestArgs['headers']['Authorization'] = b"Basic " + base64string 
Example 21
Project: warrant   Author: capless   File: aws_srp.py    License: Apache License 2.0 5 votes vote down vote up
def get_secret_hash(username, client_id, client_secret):
        message = bytearray(username + client_id, 'utf-8')
        hmac_obj = hmac.new(bytearray(client_secret, 'utf-8'), message, hashlib.sha256)
        return base64.standard_b64encode(hmac_obj.digest()).decode('utf-8') 
Example 22
Project: snowflake-connector-python   Author: snowflakedb   File: file_util.py    License: Apache License 2.0 5 votes vote down vote up
def get_digest_and_size_for_file(file_name):
        """Gets file digest and size.

        Args:
            file_name: Local path to a file.

        Returns:
            Tuple of file's digest and file size in bytes.
        """
        use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True'
        CHUNK_SIZE = 16 * 4 * 1024
        f = open(file_name, 'rb')
        if not use_openssl_only:
            m = SHA256.new()
        else:
            backend = default_backend()
            chosen_hash = hashes.SHA256()
            hasher = hashes.Hash(chosen_hash, backend)
        while True:
            chunk = f.read(CHUNK_SIZE)
            if chunk == b'':
                break
            if not use_openssl_only:
                m.update(chunk)
            else:
                hasher.update(chunk)

        statinfo = os.stat(file_name)
        file_size = statinfo.st_size
        if not use_openssl_only:
            digest = base64.standard_b64encode(m.digest()).decode(UTF8)
        else:
            digest = base64.standard_b64encode(hasher.finalize()).decode(UTF8)
        logger = getLogger(__name__)
        logger.debug('getting digest and size: %s, %s, file=%s', digest,
                     file_size, file_name)
        return digest, file_size 
Example 23
Project: bilibiliupload   Author: ForgQi   File: youku.py    License: MIT License 5 votes vote down vote up
def generateUtdid():
    timestamp = int(time.time()) - 60 * 60 * 8
    i31 = random.randrange(1 << 31)
    imei = hashCode(str(i31))
    msg = struct.pack('!2i2bi', timestamp, i31, 3, 0, imei)
    key = b'd6fc3a4a06adbde89223bvefedc24fecde188aaa9161'
    data = hmac.new(key, msg, hashlib.sha1).digest()
    msg += struct.pack('!i', hashCode(base64.standard_b64encode(data)))
    return base64.standard_b64encode(msg) 
Example 24
Project: insightconnect-plugins   Author: rapid7   File: action.py    License: MIT License 5 votes vote down vote up
def run(self, params={}):
        string = params[Input.CONTENT].encode('utf-8')
        result = base64.standard_b64encode(string)
        return {Output.DATA: result.decode('utf-8')} 
Example 25
Project: mixpanel-query-py   Author: cooncesean   File: auth.py    License: MIT License 5 votes vote down vote up
def authenticate(self, url, params):
        """
        returns a request object ready to be issued to the Mixpanel API
        """
        request_url = '{base_url}?{encoded_params}'.format(
            base_url=url,
            encoded_params=_unicode_urlencode(params)
        )
        request_headers = {
            'Authorization': 'Basic ' + _totext(base64.standard_b64encode(_tobytes("{}:".format(self.client.api_secret))))
        }
        return url_request.Request(request_url, headers=request_headers) 
Example 26
Project: ironpython2   Author: IronLanguages   File: test_base64.py    License: Apache License 2.0 5 votes vote down vote up
def test_b64encode(self):
        eq = self.assertEqual
        # Test default alphabet
        eq(base64.b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=")
        eq(base64.b64encode('\x00'), 'AA==')
        eq(base64.b64encode("a"), "YQ==")
        eq(base64.b64encode("ab"), "YWI=")
        eq(base64.b64encode("abc"), "YWJj")
        eq(base64.b64encode(""), "")
        eq(base64.b64encode("abcdefghijklmnopqrstuvwxyz"
                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                            "0123456789!@#0^&*();:<>,. []{}"),
           "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
           "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
           "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
        # Test with arbitrary alternative characters
        eq(base64.b64encode('\xd3V\xbeo\xf7\x1d', altchars='*$'), '01a*b$cd')
        # Non-bytes
        eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==')
        self.assertRaises(TypeError, base64.b64encode,
                          '\xd3V\xbeo\xf7\x1d', altchars=bytearray('*$'))
        # Test standard alphabet
        eq(base64.standard_b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=")
        eq(base64.standard_b64encode("a"), "YQ==")
        eq(base64.standard_b64encode("ab"), "YWI=")
        eq(base64.standard_b64encode("abc"), "YWJj")
        eq(base64.standard_b64encode(""), "")
        eq(base64.standard_b64encode("abcdefghijklmnopqrstuvwxyz"
                                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                     "0123456789!@#0^&*();:<>,. []{}"),
           "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
           "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
           "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
        # Non-bytes
        eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==')
        # Test with 'URL safe' alternative characters
        eq(base64.urlsafe_b64encode('\xd3V\xbeo\xf7\x1d'), '01a-b_cd')
        # Non-bytes
        eq(base64.urlsafe_b64encode(bytearray('\xd3V\xbeo\xf7\x1d')), '01a-b_cd') 
Example 27
def _base64_standard_encode(self, encode_string):
        encoder = base64.standard_b64encode(encode_string)
        return encoder 
Example 28
Project: BinderFilter   Author: dxwu   File: test_base64.py    License: MIT License 5 votes vote down vote up
def test_b64encode(self):
        eq = self.assertEqual
        # Test default alphabet
        eq(base64.b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=")
        eq(base64.b64encode('\x00'), 'AA==')
        eq(base64.b64encode("a"), "YQ==")
        eq(base64.b64encode("ab"), "YWI=")
        eq(base64.b64encode("abc"), "YWJj")
        eq(base64.b64encode(""), "")
        eq(base64.b64encode("abcdefghijklmnopqrstuvwxyz"
                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                            "0123456789!@#0^&*();:<>,. []{}"),
           "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
           "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
           "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
        # Test with arbitrary alternative characters
        eq(base64.b64encode('\xd3V\xbeo\xf7\x1d', altchars='*$'), '01a*b$cd')
        # Non-bytes
        eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==')
        self.assertRaises(TypeError, base64.b64encode,
                          '\xd3V\xbeo\xf7\x1d', altchars=bytearray('*$'))
        # Test standard alphabet
        eq(base64.standard_b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=")
        eq(base64.standard_b64encode("a"), "YQ==")
        eq(base64.standard_b64encode("ab"), "YWI=")
        eq(base64.standard_b64encode("abc"), "YWJj")
        eq(base64.standard_b64encode(""), "")
        eq(base64.standard_b64encode("abcdefghijklmnopqrstuvwxyz"
                                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                     "0123456789!@#0^&*();:<>,. []{}"),
           "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
           "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
           "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
        # Non-bytes
        eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==')
        # Test with 'URL safe' alternative characters
        eq(base64.urlsafe_b64encode('\xd3V\xbeo\xf7\x1d'), '01a-b_cd')
        # Non-bytes
        eq(base64.urlsafe_b64encode(bytearray('\xd3V\xbeo\xf7\x1d')), '01a-b_cd') 
Example 29
Project: plugin.video.netflix   Author: CastagnaIT   File: android_crypto.py    License: MIT License 5 votes vote down vote up
def encrypt(self, plaintext, esn):  # pylint: disable=unused-argument
        """
        Encrypt the given Plaintext with the encryption key
        :param plaintext:
        :return: Serialized JSON String of the encryption Envelope
        """
        from os import urandom
        init_vector = bytearray(urandom(16))
        # Add PKCS5Padding
        pad = 16 - len(plaintext) % 16
        padded_data = plaintext + ''.join([chr(pad)] * pad)
        encrypted_data = self.crypto_session.Encrypt(bytearray(self.key_id),
                                                     bytearray(padded_data.encode('utf-8')),
                                                     init_vector)

        if not encrypted_data:
            raise MSLError('Widevine CryptoSession encrypt failed!')

        return json.dumps({
            'version': 1,
            'ciphertext': base64.standard_b64encode(encrypted_data).decode('utf-8'),
            'sha256': 'AA==',
            'keyid': base64.standard_b64encode(self.key_id).decode('utf-8'),
            # 'cipherspec' : 'AES/CBC/PKCS5Padding',
            'iv': base64.standard_b64encode(init_vector).decode('utf-8')
        }) 
Example 30
Project: plugin.video.netflix   Author: CastagnaIT   File: android_crypto.py    License: MIT License 5 votes vote down vote up
def sign(self, message):
        """Sign a message"""
        signature = self.crypto_session.Sign(bytearray(self.hmac_key_id),
                                             bytearray(message.encode('utf-8')))
        if not signature:
            raise MSLError('Widevine CryptoSession sign failed!')
        return base64.standard_b64encode(signature).decode('utf-8')