本文整理匯總了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
示例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
}
}]
示例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)
示例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)
示例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
示例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)
示例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()
示例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)
示例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)
示例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"])
)
示例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)
示例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))
示例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>")
示例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}
示例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}