当前位置: 首页>>代码示例>>Python>>正文


Python base64.standard_b64encode方法代码示例

本文整理汇总了Python中base64.standard_b64encode方法的典型用法代码示例。如果您正苦于以下问题:Python base64.standard_b64encode方法的具体用法?Python base64.standard_b64encode怎么用?Python base64.standard_b64encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在base64的用法示例。


在下文中一共展示了base64.standard_b64encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: process_challenge

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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 
开发者ID:capless,项目名称:warrant,代码行数:26,代码来源:aws_srp.py

示例2: key_request_data

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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
            }
        }] 
开发者ID:CastagnaIT,项目名称:plugin.video.netflix,代码行数:25,代码来源:android_crypto.py

示例3: encrypt

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
def encrypt(self, plaintext, esn):
        """
        Encrypt the given Plaintext with the encryption key
        :param plaintext:
        :return: Serialized JSON String of the encryption Envelope
        """
        init_vector = get_random_bytes(16)
        cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)
        ciphertext = base64.standard_b64encode(
            cipher.encrypt(Padding.pad(plaintext.encode('utf-8'), 16))).decode('utf-8')
        encryption_envelope = {
            'ciphertext': ciphertext,
            'keyid': '_'.join((esn, str(self.sequence_number))),
            'sha256': 'AA==',
            'iv': base64.standard_b64encode(init_vector).decode('utf-8')
        }
        return json.dumps(encryption_envelope) 
开发者ID:CastagnaIT,项目名称:plugin.video.netflix,代码行数:19,代码来源:default_crypto.py

示例4: inject

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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) 
开发者ID:lightstep,项目名称:lightstep-tracer-python,代码行数:20,代码来源:lightstep_binary_propagator.py

示例5: get_content_md5

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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 
开发者ID:tencentyun,项目名称:cos-python-sdk-v5,代码行数:23,代码来源:cos_comm.py

示例6: _from_inst

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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) 
开发者ID:cyberdb,项目名称:Cloudroid,代码行数:21,代码来源:message_conversion.py

示例7: _update_marathon_json

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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() 
开发者ID:mesosphere,项目名称:dcos-kafka-service,代码行数:26,代码来源:release_builder.py

示例8: testImages

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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) 
开发者ID:FSecureLABS,项目名称:Jandroid,代码行数:27,代码来源:style_sheet_unittest.py

示例9: contents_with_inlined_images

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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) 
开发者ID:FSecureLABS,项目名称:Jandroid,代码行数:20,代码来源:style_sheet.py

示例10: get_state

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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"])
            ) 
开发者ID:Azure-Samples,项目名称:MLOpsDatabricks,代码行数:21,代码来源:cluster.py

示例11: save_pem

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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) 
开发者ID:Deltares,项目名称:aqua-monitor,代码行数:27,代码来源:pem.py

示例12: get

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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)) 
开发者ID:GoogleCloudPlatform,项目名称:django-cloud-deploy,代码行数:18,代码来源:container_test.py

示例13: get

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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>") 
开发者ID:mozilla,项目名称:jupyter-notebook-gist,代码行数:21,代码来源:handlers.py

示例14: sign

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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} 
开发者ID:Crypto-toolbox,项目名称:bitex,代码行数:24,代码来源:bitfinex.py

示例15: sign

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64encode [as 别名]
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} 
开发者ID:Crypto-toolbox,项目名称:bitex,代码行数:20,代码来源:gemini.py


注:本文中的base64.standard_b64encode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。