本文整理汇总了Python中base64.standard_b64decode方法的典型用法代码示例。如果您正苦于以下问题:Python base64.standard_b64decode方法的具体用法?Python base64.standard_b64decode怎么用?Python base64.standard_b64decode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类base64
的用法示例。
在下文中一共展示了base64.standard_b64decode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process_challenge
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [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: run
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def run(self, params={}):
try:
data = params.get(Input.BASE64)
errors = params.get(Input.ERRORS)
result = base64.standard_b64decode(data)
if errors in ["replace", "ignore"]:
return {Output.DATA: result.decode('utf-8', errors=errors)}
else:
return {Output.DATA: result.decode('utf-8')}
except Exception as e:
self.logger.error("An error has occurred while decoding ", e)
raise PluginException(
cause="Failed to decode because valid base64 input was not provided.",
assistance='If you would like continue to attempt to decode the input try setting the value of the error field to ignore errors or to replace the characters.',
data=e
)
示例3: test_b64decode_invalid_chars
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def test_b64decode_invalid_chars(self):
# issue 1466065: Test some invalid characters.
tests = ((b'%3d==', b'\xdd'),
(b'$3d==', b'\xdd'),
(b'[==', b''),
(b'YW]3=', b'am'),
(b'3{d==', b'\xdd'),
(b'3d}==', b'\xdd'),
(b'@@', b''),
(b'!', b''),
(b'YWJj\nYWI=', b'abcab'))
for bstr, res in tests:
self.assertEqual(base64.b64decode(bstr), res)
self.assertEqual(base64.standard_b64decode(bstr), res)
self.assertEqual(base64.urlsafe_b64decode(bstr), res)
# Normal alphabet characters not discarded when alternative given
res = b'\xFB\xEF\xBE\xFF\xFF\xFF'
self.assertEqual(base64.b64decode(b'++[[//]]', b'[]'), res)
self.assertEqual(base64.urlsafe_b64decode(b'++--//__'), res)
示例4: do_POST
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def do_POST(self):
"""Loads the licence for the requested resource"""
try:
url_parse = urlparse(self.path)
common.debug('Handling HTTP POST IPC call to {}', url_parse.path)
if '/license' not in url_parse:
self.send_response(404)
self.end_headers()
return
length = int(self.headers.get('content-length', 0))
data = self.rfile.read(length).decode('utf-8').split('!')
b64license = self.server.msl_handler.get_license(
challenge=data[0], sid=base64.standard_b64decode(data[1]).decode('utf-8'))
self.send_response(200)
self.end_headers()
self.wfile.write(base64.standard_b64decode(b64license))
except Exception as exc:
import traceback
common.error(g.py2_decode(traceback.format_exc(), 'latin-1'))
self.send_response(500 if isinstance(exc, MSLError) else 400)
self.end_headers()
示例5: as_file
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def as_file(self):
"""If obj[%data_key_name] exists, return name of a file with base64
decoded obj[%data_key_name] content otherwise obj[%file_key_name]."""
use_data_if_no_file = not self._file and self._data
if use_data_if_no_file:
if self._base64_file_content:
if isinstance(self._data, str):
content = self._data.encode()
else:
content = self._data
self._file = _create_temp_file_with_content(
base64.standard_b64decode(content))
else:
self._file = _create_temp_file_with_content(self._data)
if self._file and not os.path.isfile(self._file):
raise ConfigException("File does not exists: %s" % self._file)
return self._file
示例6: _urlsafe_b64decode
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def _urlsafe_b64decode(self, value):
value = value.rstrip('\r\n') # some encoders like to append a newline...
try:
# `base64.urlsafe_b64decode()` just ignores illegal
# characters *but* we want to be *more strict*
if not self._URLSAFE_B64_VALID_CHARACTERS.issuperset(value):
raise ValueError
# `base64.urlsafe_b64decode()` (contrary to `base64.standard_b64decode()`)
# does *not* accept unicode strings (even not pure-ASCII ones) :-/
value = string_as_bytes(value)
value = base64.urlsafe_b64decode(value)
except (ValueError, TypeError): # (TypeError is raised on incorrect Base64 padding)
raise FieldValueError(public_message=(
'"{}" is not a valid URL-safe-Base64-encoded string '
'[see: RFC 4648, section 5]'.format(ascii_str(value))))
return value
示例7: _update_marathon_json
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [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: _read_auth_response
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def _read_auth_response(self, response):
"""
Read the authentication request's response sent by the database
and validate the server signature which was returned.
:param response: Response from the database
:raises: ReqlDriverError | ReqlAuthError
:return: None
"""
json_response = self._decode_json_response(response, with_utf8=True)
(
first_client_message,
authentication,
) = self._get_authentication_and_first_client_message(json_response)
server_signature = base64.standard_b64decode(authentication[b"v"])
if not self._compare_digest(server_signature, self._server_signature):
raise ReqlAuthError("Invalid server signature", self._host, self._port)
self._next_state()
示例9: response_from_kitty
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def response_from_kitty(self, boss: Boss, window: Optional[Window], payload_get: PayloadGetType) -> ResponseType:
windows = [boss.active_window]
match = payload_get('match')
if match:
windows = list(boss.match_windows(match))
mt = payload_get('match_tab')
if mt:
windows = []
tabs = tuple(boss.match_tabs(mt))
if not tabs:
raise MatchError(payload_get('match_tab'), 'tabs')
for tab in tabs:
windows += tuple(tab)
encoding, _, q = payload_get('data').partition(':')
if encoding == 'text':
data = q.encode('utf-8')
elif encoding == 'base64':
data = base64.standard_b64decode(q)
else:
raise TypeError(f'Invalid encoding for send-text data: {encoding}')
for window in windows:
if window is not None:
window.write_to_child(data)
示例10: _login
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def _login(sess, cookies_file=None, cookies_base64=None):
if cookies_file is None:
if cookies_base64 is None:
cookies_base64 = os.environ.get('DL_COURSERA_COOKIES_BASE64')
assert cookies_base64
cookies = base64.standard_b64decode(cookies_base64)
with TmpFile() as tmpfile:
with open(tmpfile, 'wb') as ofs:
ofs.write(cookies)
cj = MozillaCookieJar()
cj.load(tmpfile)
else:
cj = MozillaCookieJar()
cj.load(cookies_file)
sess.cookies.update(cj)
示例11: sign_extract
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def sign_extract(signature):
if not signature:
return None, None, None
try:
text = base64.standard_b64decode(signature)
except:
return None, None, None
part = text.split(':')
if len(part) != 3:
return None, None, None
user = part[0].strip('\r\n\t ')
try:
ts = long(part[1])
except:
return None, None, None
verify = part[2].strip('\r\n\t ').lower()
return user, ts, verify
# 检查文件名
示例12: save_crawled_screeshot
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def save_crawled_screeshot(b64_screenshot, max_size, f_save=False):
screenshot_size = (len(b64_screenshot)*3) /4
if screenshot_size < max_size or f_save:
image_content = base64.standard_b64decode(b64_screenshot.encode())
sha256_string = sha256(image_content).hexdigest()
filepath = get_screenshot_filepath(sha256_string)
if os.path.isfile(filepath):
#print('File already exist')
return sha256_string
# create dir
dirname = os.path.dirname(filepath)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(filepath, 'wb') as f:
f.write(image_content)
return sha256_string
return False
示例13: IsValidBase64String
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def IsValidBase64String(string_to_validate):
"""Verifies if a string is a valid Base64 encoded string, after replacing '-' with '/'
:param string string_to_validate:
String to validate.
:return:
Whether given string is a valid base64 string or not.
:rtype: str
"""
# '-' is not supported char for decoding in Python(same as C# and Java) which has similar logic while parsing ResourceID generated by backend
try:
buffer = base64.standard_b64decode(string_to_validate.replace('-', '/'))
if len(buffer) != 4:
return False
except Exception as e:
if six.PY2:
e = e.message
if type(e) == binascii.Error:
return False
else:
raise e
return True
示例14: check_originating_identity
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def check_originating_identity():
"""
Check and decode the "X-Broker-API-Originating-Identity" header
https://github.com/openservicebrokerapi/servicebroker/blob/v2.13/spec.md#originating-identity
"""
from flask import request, json
if "X-Broker-API-Originating-Identity" in request.headers:
try:
platform, value = request.headers["X-Broker-API-Originating-Identity"].split(None, 1)
request.originating_identity = {
'platform': platform,
'value': json.loads(base64.standard_b64decode(value))
}
except ValueError as e:
return to_json_response(ErrorResponse(
description='Improper "X-Broker-API-Originating-Identity" header. ' + str(e))
), HTTPStatus.BAD_REQUEST
else:
request.originating_identity = None
示例15: run
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import standard_b64decode [as 别名]
def run(self, params={}):
raw = base64.standard_b64decode(params[Input.BYTES])
md5 = hashlib.md5(raw).hexdigest() # nosec
sha1 = hashlib.sha1(raw).hexdigest() # nosec
sha256 = hashlib.sha256(raw).hexdigest()
sha512 = hashlib.sha512(raw).hexdigest()
hashes = {
Output.MD5: md5,
Output.SHA1: sha1,
Output.SHA256: sha256,
Output.SHA512: sha512,
}
return hashes