本文整理匯總了Python中base64.urlsafe_b64decode方法的典型用法代碼示例。如果您正苦於以下問題:Python base64.urlsafe_b64decode方法的具體用法?Python base64.urlsafe_b64decode怎麽用?Python base64.urlsafe_b64decode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類base64
的用法示例。
在下文中一共展示了base64.urlsafe_b64decode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: loads
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def loads(self, bstruct):
"""
Given a ``bstruct`` (a bytestring), verify the signature and then
deserialize and return the deserialized value.
A ``ValueError`` will be raised if the signature fails to validate.
"""
try:
b64padding = b'=' * (-len(bstruct) % 4)
fstruct = base64.urlsafe_b64decode(bytes_(bstruct) + b64padding)
except (binascii.Error, TypeError) as e:
raise ValueError('Badly formed base64 data: %s' % e)
cstruct = fstruct[self.digest_size:]
expected_sig = fstruct[:self.digest_size]
sig = hmac.new(
self.salted_secret, bytes_(cstruct), self.digestmod).digest()
if strings_differ(sig, expected_sig):
raise ValueError('Invalid signature')
return self.serializer.loads(cstruct)
示例2: test_returns_http2_settings
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def test_returns_http2_settings(self, frame_factory):
"""
Calling initiate_upgrade_connection returns a base64url encoded
Settings frame with the settings used by the connection.
"""
conn = h2.connection.H2Connection()
data = conn.initiate_upgrade_connection()
# The base64 encoding must not be padded.
assert not data.endswith(b'=')
# However, SETTINGS frames should never need to be padded.
decoded_frame = base64.urlsafe_b64decode(data)
expected_frame = frame_factory.build_settings_frame(
settings=conn.local_settings
)
assert decoded_frame == expected_frame.serialize_body()
示例3: is_valid_user_id
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def is_valid_user_id(b64_content: str) -> bool:
"""
Check potential token to see if it contains a valid Discord user ID.
See: https://discordapp.com/developers/docs/reference#snowflakes
"""
b64_content = utils.pad_base64(b64_content)
try:
decoded_bytes = base64.urlsafe_b64decode(b64_content)
string = decoded_bytes.decode('utf-8')
# isdigit on its own would match a lot of other Unicode characters, hence the isascii.
return string.isascii() and string.isdigit()
except (binascii.Error, ValueError):
return False
示例4: is_valid_timestamp
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def is_valid_timestamp(b64_content: str) -> bool:
"""
Return True if `b64_content` decodes to a valid timestamp.
If the timestamp is greater than the Discord epoch, it's probably valid.
See: https://i.imgur.com/7WdehGn.png
"""
b64_content = utils.pad_base64(b64_content)
try:
decoded_bytes = base64.urlsafe_b64decode(b64_content)
timestamp = int.from_bytes(decoded_bytes, byteorder="big")
except (binascii.Error, ValueError) as e:
log.debug(f"Failed to decode token timestamp '{b64_content}': {e}")
return False
# Seems like newer tokens don't need the epoch added, but add anyway since an upper bound
# is not checked.
if timestamp + TOKEN_EPOCH >= DISCORD_EPOCH:
return True
else:
log.debug(f"Invalid token timestamp '{b64_content}': smaller than Discord epoch")
return False
示例5: b64d
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def b64d(b):
"""Decode some base64-encoded bytes.
Raises Exception if the string contains invalid characters or padding.
:param b: bytes
"""
cb = b.rstrip(b"=") # shouldn't but there you are
# Python's base64 functions ignore invalid characters, so we need to
# check for them explicitly.
b64_re = re.compile(b"^[A-Za-z0-9_-]*$")
if not b64_re.match(cb):
raise Exception(cb, "base64-encoded data contains illegal characters")
if cb == b:
b = JWT.add_padding(b)
return base64.urlsafe_b64decode(b)
示例6: decode_field
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def decode_field(self, field, value):
"""Decode a JSON value to a python value.
Args:
field: A ProtoRPC field instance.
value: A serialized JSON value.
Returns:
A Python value compatible with field.
"""
# Override BytesField handling. Client libraries typically use a url-safe
# encoding. b64decode doesn't handle these gracefully. urlsafe_b64decode
# handles both cases safely. Also add padding if the padding is incorrect.
if isinstance(field, messages.BytesField):
try:
# Need to call str(value) because ProtoRPC likes to pass values
# as unicode, and urlsafe_b64decode can only handle bytes.
padded_value = self.__pad_value(str(value), 4, '=')
return base64.urlsafe_b64decode(padded_value)
except (TypeError, UnicodeEncodeError), err:
raise messages.DecodeError('Base64 decoding error: %s' % err)
示例7: _decode_uuid_line
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def _decode_uuid_line(line, passwd):
decoded = base64.urlsafe_b64decode(line)
if IS_WIN:
key = scrypt.hash(passwd, socket.gethostname())
key = base64.urlsafe_b64encode(key[:32])
try:
f = Fernet(key, backend=crypto_backend)
maybe_decrypted = f.decrypt(key)
except Exception:
return None
else:
try:
maybe_decrypted = scrypt.decrypt(decoded, passwd, maxtime=0.1)
except scrypt.error:
return None
match = re.findall("userid\:(.+)\:uuid\:(.+)", maybe_decrypted)
if match:
return match[0]
示例8: test_b64decode_invalid_chars
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_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)
示例9: sign_hmac
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def sign_hmac(secret, payload):
"""Returns a base64-encoded HMAC-SHA1 signature of a given string.
:param secret: The key used for the signature, base64 encoded.
:type secret: string
:param payload: The payload to sign.
:type payload: string
:rtype: string
"""
payload = payload.encode('ascii', 'strict')
secret = secret.encode('ascii', 'strict')
sig = hmac.new(base64.urlsafe_b64decode(secret), payload, hashlib.sha1)
out = base64.urlsafe_b64encode(sig.digest())
return out.decode('utf-8')
示例10: b64url_decode
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def b64url_decode(s):
return base64.urlsafe_b64decode(b64_restore_padding(s))
示例11: extract_real_url_from_embedded_url
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def extract_real_url_from_embedded_url(embedded_url):
"""
將 embed_real_url_to_embedded_url() 編碼後的url轉換為原來的帶有參數的url
`cdn_redirect_encode_query_str_into_url`設置依賴於本函數, 詳細說明請看配置文件中這個參數的部分
eg: https://cdn.domain.com/a.php_zm24_.cT1zb21ldGhpbmc=._zm24_.css
---> https://foo.com/a.php?q=something (assume it returns an css) (base64 only)
eg2: https://cdn.domain.com/a/b/_zm24_.bG92ZT1saXZl._zm24_.jpg
---> https://foo.com/a/b/?love=live (assume it returns an jpg) (base64 only)
eg3: https://cdn.domain.com/a/b/_zm24z_.[some long long base64 encoded string]._zm24_.jpg
---> https://foo.com/a/b/?love=live[and a long long query string] (assume it returns an jpg) (gzip + base64)
eg4:https://cdn.domain.com/a (no change)
---> (no query string): https://foo.com/a (assume it returns an png) (no change)
:param embedded_url: 可能被編碼的URL
:return: 如果傳入的是編碼後的URL, 則返回解碼後的URL, 否則返回None
:type embedded_url: str
:rtype: Union[str, None]
"""
if '._' + cdn_url_query_encode_salt + '_.' not in embedded_url[-15:]: # check url mark
return None
m = regex_extract_base64_from_embedded_url.search(embedded_url)
b64 = get_group('b64', m)
# 'https://cdn.domain.com/a.php_zm24_.cT1zb21ldGhpbmc=._zm24_.css'
# real_request_url_no_query ---> 'https://cdn.domain.com/a.php'
real_request_url_no_query = embedded_url[:m.span()[0]]
query_string_byte = base64.urlsafe_b64decode(b64)
is_gzipped = get_group('gzip', m)
if is_gzipped:
query_string_byte = zlib.decompress(query_string_byte)
query_string = query_string_byte.decode(encoding='utf-8')
result = urljoin(real_request_url_no_query, '?' + query_string)
# dbgprint('extract:', embedded_url, 'to', result)
return result
示例12: load_friends
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def load_friends(self):
my_friends = self.requester.get_friends(self.username)
for user in my_friends["friends"]:
if user['username'] != self.username:
friend_frame = ttk.Frame(self.canvas_frame)
friend_avatar_path = os.path.join(friend_avatars_dir, f"{user['username']}.png")
if user["avatar"]:
with open(friend_avatar_path, 'wb') as friend_avatar:
img = base64.urlsafe_b64decode(user['avatar'])
friend_avatar.write(img)
else:
friend_avatar_path = default_avatar_path
profile_photo = tk.PhotoImage(file=friend_avatar_path)
profile_photo_label = ttk.Label(friend_frame, image=profile_photo)
profile_photo_label.image = profile_photo
friend_name = ttk.Label(friend_frame, text=user['real_name'], anchor=tk.W)
message_this_friend = partial(self.open_chat_window, username=user["username"], real_name=user["real_name"], avatar=friend_avatar_path)
block_this_friend = partial(self.block_friend, username=user["username"])
message_button = ttk.Button(friend_frame, text="Chat", command=message_this_friend)
block_button = ttk.Button(friend_frame, text="Block", command=block_this_friend)
profile_photo_label.pack(side=tk.LEFT)
friend_name.pack(side=tk.LEFT)
message_button.pack(side=tk.RIGHT)
block_button.pack(side=tk.RIGHT, padx=(0, 30))
friend_frame.pack(fill=tk.X, expand=1)
示例13: _ParseScanReportXML
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def _ParseScanReportXML(body, content_type):
if content_type != 'Content-Type: text/xml; name=report.xml':
raise ValueError("Invalid content type")
return as_xml(base64.urlsafe_b64decode(body))
示例14: _ParseScanReportCSV
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def _ParseScanReportCSV(body, content_type):
if content_type != 'Content-Type: text/csv; name=report.csv':
raise ValueError("Invalid content type")
csv_ = base64.urlsafe_b64decode(body).decode('utf8')
report_data = csv.DictReader(io.StringIO(csv_))
return report_data
#
# The following functions implement the Role Management API:
# =========================================================
示例15: encrypt
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import urlsafe_b64decode [as 別名]
def encrypt(self, iterations: int = 100_000) -> bytes:
"""Encrypt secret."""
salt = secrets.token_bytes(16)
key = self.__derive_key(salt, iterations)
return urlsafe_b64encode(
b"%b%b%b" % (salt,
iterations.to_bytes(4, "big"),
urlsafe_b64decode(Fernet(key).encrypt(self.secret))))