Python base64.urlsafe_b64decode() Examples
The following are 30
code examples of base64.urlsafe_b64decode().
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 also want to check out all available functions/classes of the module
base64
, or try the search function
.
Example #1
Source File: client.py From google-maps-services-python with Apache License 2.0 | 6 votes |
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')
Example #2
Source File: protojson.py From endpoints-python with Apache License 2.0 | 6 votes |
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)
Example #3
Source File: JWT.py From im with GNU General Public License v3.0 | 6 votes |
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)
Example #4
Source File: token_remover.py From bot with MIT License | 6 votes |
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
Example #5
Source File: token_remover.py From bot with MIT License | 6 votes |
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
Example #6
Source File: test_base64.py From ironpython2 with Apache License 2.0 | 6 votes |
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)
Example #7
Source File: test_h2_upgrade.py From hyper-h2 with MIT License | 6 votes |
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()
Example #8
Source File: uuid_map.py From bitmask-dev with GNU General Public License v3.0 | 6 votes |
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]
Example #9
Source File: cookies.py From pledgeservice with Apache License 2.0 | 6 votes |
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)
Example #10
Source File: friendslist.py From Tkinter-GUI-Programming-by-Example with MIT License | 6 votes |
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)
Example #11
Source File: test_base64.py From oss-ftp with MIT License | 5 votes |
def test_b64decode(self): eq = self.assertEqual eq(base64.b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") eq(base64.b64decode('AA=='), '\x00') eq(base64.b64decode("YQ=="), "a") eq(base64.b64decode("YWI="), "ab") eq(base64.b64decode("YWJj"), "abc") eq(base64.b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}") eq(base64.b64decode(''), '') # Test with arbitrary alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\xd3V\xbeo\xf7\x1d') # Non-bytes eq(base64.b64decode(bytearray("YWJj")), "abc") # Test standard alphabet eq(base64.standard_b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") eq(base64.standard_b64decode("YQ=="), "a") eq(base64.standard_b64decode("YWI="), "ab") eq(base64.standard_b64decode("YWJj"), "abc") eq(base64.standard_b64decode(""), "") eq(base64.standard_b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}") # Non-bytes eq(base64.standard_b64decode(bytearray("YWJj")), "abc") # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\xd3V\xbeo\xf7\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\xd3V\xbeo\xf7\x1d')
Example #12
Source File: crypt.py From billing-export-python with Apache License 2.0 | 5 votes |
def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded)
Example #13
Source File: util.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def urlsafe_b64decode(data): """urlsafe_b64decode without padding""" pad = b'=' * (4 - (len(data) & 3)) return base64.urlsafe_b64decode(data + pad)
Example #14
Source File: client.py From billing-export-python with Apache License 2.0 | 5 votes |
def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded)
Example #15
Source File: default_crypto.py From plugin.video.netflix with MIT License | 5 votes |
def _base64key_decode(b64): padding = len(b64) % 4 if padding != 0: b64 += '=' * (4 - padding) return base64.urlsafe_b64decode(b64.encode('utf8'))
Example #16
Source File: test_base64.py From BinderFilter with MIT License | 5 votes |
def test_b64decode(self): eq = self.assertEqual eq(base64.b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") eq(base64.b64decode('AA=='), '\x00') eq(base64.b64decode("YQ=="), "a") eq(base64.b64decode("YWI="), "ab") eq(base64.b64decode("YWJj"), "abc") eq(base64.b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}") eq(base64.b64decode(''), '') # Test with arbitrary alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\xd3V\xbeo\xf7\x1d') # Non-bytes eq(base64.b64decode(bytearray("YWJj")), "abc") # Test standard alphabet eq(base64.standard_b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") eq(base64.standard_b64decode("YQ=="), "a") eq(base64.standard_b64decode("YWI="), "ab") eq(base64.standard_b64decode("YWJj"), "abc") eq(base64.standard_b64decode(""), "") eq(base64.standard_b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}") # Non-bytes eq(base64.standard_b64decode(bytearray("YWJj")), "abc") # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\xd3V\xbeo\xf7\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\xd3V\xbeo\xf7\x1d')
Example #17
Source File: itsdangerous.py From RSSNewsGAE with Apache License 2.0 | 5 votes |
def base64_decode(string): """base64 decodes a single bytestring (and is tolerant to getting called with a unicode string). The result is also a bytestring. """ string = want_bytes(string, encoding='ascii', errors='ignore') return base64.urlsafe_b64decode(string + b'=' * (-len(string) % 4))
Example #18
Source File: client.py From sndlatr with Apache License 2.0 | 5 votes |
def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded)
Example #19
Source File: alice.py From aries-cloudagent-python with Apache License 2.0 | 5 votes |
def input_invitation(agent): async for details in prompt_loop("Invite details: "): b64_invite = None try: url = urlparse(details) query = url.query if query and "c_i=" in query: pos = query.index("c_i=") + 4 b64_invite = query[pos:] else: b64_invite = details except ValueError: b64_invite = details if b64_invite: try: padlen = 4 - len(b64_invite) % 4 if padlen <= 2: b64_invite += "=" * padlen invite_json = base64.urlsafe_b64decode(b64_invite) details = invite_json.decode("utf-8") except binascii.Error: pass except UnicodeDecodeError: pass if details: try: json.loads(details) break except json.JSONDecodeError as e: log_msg("Invalid invitation:", str(e)) with log_timer("Connect duration:"): connection = await agent.admin_POST("/connections/receive-invitation", details) agent.connection_id = connection["connection_id"] log_json(connection, label="Invitation response:") await agent.detect_connection()
Example #20
Source File: crypt.py From splunk-ref-pas-code with Apache License 2.0 | 5 votes |
def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded)
Example #21
Source File: client.py From splunk-ref-pas-code with Apache License 2.0 | 5 votes |
def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded)
Example #22
Source File: __init__.py From faces with GNU General Public License v2.0 | 5 votes |
def base64url_decode(input): input += b('=') * (4 - (len(input) % 4)) return base64.urlsafe_b64decode(input)
Example #23
Source File: __init__.py From faces with GNU General Public License v2.0 | 5 votes |
def base64url_decode(input): input += b('=') * (4 - (len(input) % 4)) return base64.urlsafe_b64decode(input)
Example #24
Source File: main.py From aiohttp-session with Apache License 2.0 | 5 votes |
def make_app(): app = web.Application() # secret_key must be 32 url-safe base64-encoded bytes fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) setup(app, EncryptedCookieStorage(secret_key)) app.router.add_get('/', handler) return app
Example #25
Source File: __init__.py From lokey with GNU General Public License v3.0 | 5 votes |
def base64_to_long(data): if isinstance(data, six.text_type): data = data.encode("ascii") # urlsafe_b64decode will happily convert b64encoded data _d = base64.urlsafe_b64decode(bytes(data) + b'==') return intarr2long(struct.unpack('%sB' % len(_d), _d))
Example #26
Source File: util.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def urlsafe_b64decode(data): """urlsafe_b64decode without padding""" pad = b'=' * (4 - (len(data) & 3)) return base64.urlsafe_b64decode(data + pad)
Example #27
Source File: test_ece.py From encrypted-content-encoding with MIT License | 5 votes |
def b64d(arg): if arg is None: return None return base64.urlsafe_b64decode(str(arg) + '===='[:len(arg) % 4:])
Example #28
Source File: test_base64.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_b64decode(self): eq = self.assertEqual eq(base64.b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") eq(base64.b64decode('AA=='), '\x00') eq(base64.b64decode("YQ=="), "a") eq(base64.b64decode("YWI="), "ab") eq(base64.b64decode("YWJj"), "abc") eq(base64.b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}") eq(base64.b64decode(''), '') # Test with arbitrary alternative characters eq(base64.b64decode('01a*b$cd', altchars='*$'), '\xd3V\xbeo\xf7\x1d') # Non-bytes eq(base64.b64decode(bytearray("YWJj")), "abc") # Test standard alphabet eq(base64.standard_b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") eq(base64.standard_b64decode("YQ=="), "a") eq(base64.standard_b64decode("YWI="), "ab") eq(base64.standard_b64decode("YWJj"), "abc") eq(base64.standard_b64decode(""), "") eq(base64.standard_b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789!@#0^&*();:<>,. []{}") # Non-bytes eq(base64.standard_b64decode(bytearray("YWJj")), "abc") # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64decode('01a-b_cd'), '\xd3V\xbeo\xf7\x1d') # Non-bytes eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\xd3V\xbeo\xf7\x1d')
Example #29
Source File: serializers.py From desec-stack with MIT License | 5 votes |
def _unpack_code(cls, code): try: payload_enc = urlsafe_b64decode(code.encode()) payload = crypto.decrypt(payload_enc, context='desecapi.serializers.AuthenticatedActionSerializer', ttl=settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE.total_seconds()) return json.loads(payload.decode()) except (TypeError, UnicodeDecodeError, UnicodeEncodeError, json.JSONDecodeError, binascii.Error): raise ValueError
Example #30
Source File: crypto.py From django-cryptography with BSD 3-Clause "New" or "Revised" License | 5 votes |
def decrypt(self, token, ttl=None): try: data = base64.urlsafe_b64decode(token) except (TypeError, Error): raise InvalidToken return super(Fernet, self).decrypt(data, ttl)