Python base64.urlsafe_b64decode() Examples

The following are 30 code examples for showing how to use base64.urlsafe_b64decode(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module base64 , or try the search function .

Example 1
Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: friendslist.py    License: MIT License 6 votes vote down vote up
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 2
Project: hyper-h2   Author: python-hyper   File: test_h2_upgrade.py    License: MIT License 6 votes vote down vote up
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 3
Project: bot   Author: python-discord   File: token_remover.py    License: MIT License 6 votes vote down vote up
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 4
Project: bot   Author: python-discord   File: token_remover.py    License: MIT License 6 votes vote down vote up
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
Project: im   Author: grycap   File: JWT.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 6
Project: endpoints-python   Author: cloudendpoints   File: protojson.py    License: Apache License 2.0 6 votes vote down vote up
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 7
Project: pledgeservice   Author: MayOneUS   File: cookies.py    License: Apache License 2.0 6 votes vote down vote up
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 8
Project: bitmask-dev   Author: leapcode   File: uuid_map.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: ironpython2   Author: IronLanguages   File: test_base64.py    License: Apache License 2.0 6 votes vote down vote up
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 10
Project: google-maps-services-python   Author: googlemaps   File: client.py    License: Apache License 2.0 6 votes vote down vote up
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 11
Project: pywarp   Author: pyauth   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def b64url_decode(s):
    return base64.urlsafe_b64decode(b64_restore_padding(s)) 
Example 12
Project: zmirror   Author: aploium   File: utils.py    License: MIT License 5 votes vote down vote up
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 
Example 13
Project: nexpose-client-python   Author: rapid7   File: nexpose.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)) 
Example 14
Project: nexpose-client-python   Author: rapid7   File: nexpose.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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:
    # ========================================================= 
Example 15
Project: shhh   Author: smallwat3r   File: utils.py    License: MIT License 5 votes vote down vote up
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)))) 
Example 16
Project: shhh   Author: smallwat3r   File: utils.py    License: MIT License 5 votes vote down vote up
def decrypt(self) -> str:
        """Decrypt secret."""
        decoded = urlsafe_b64decode(self.secret)
        salt, iteration, message = (decoded[:16], decoded[16:20],
                                    urlsafe_b64encode(decoded[20:]))
        iterations = int.from_bytes(iteration, "big")
        key = self.__derive_key(salt, iterations)
        return Fernet(key).decrypt(message).decode("utf-8") 
Example 17
Project: razzy-spinner   Author: rafasashi   File: wordnet_app.py    License: GNU General Public License v3.0 5 votes vote down vote up
def decode(string):
        """
        Decode a reference encoded with Reference.encode
        """
        string = base64.urlsafe_b64decode(string.encode())
        word, synset_relations = pickle.loads(string)
        return Reference(word, synset_relations) 
Example 18
Project: pymsl   Author: truedread   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def webcrypto_b64decode(b64):
    """
    webcrypto_b64decode()

    @param b64: URL safe encoded base64 string lacking padding
                (most likely from WebCrypto API)

    @return: Bytes from decoding base64 string
    """

    padding = len(b64) % 4
    if padding != 0:
        b64 += '=' * (4 - padding)
    return base64.urlsafe_b64decode(b64.encode('utf8')) 
Example 19
Project: gist-alfred   Author: danielecook   File: utils.py    License: MIT License 5 votes vote down vote up
def base64url_decode(input):
    if isinstance(input, text_type):
        input = input.encode('ascii')

    rem = len(input) % 4

    if rem > 0:
        input += b'=' * (4 - rem)

    return base64.urlsafe_b64decode(input) 
Example 20
Project: Telethon   Author: LonamiWebs   File: utils.py    License: MIT License 5 votes vote down vote up
def _decode_telegram_base64(string):
    """
    Decodes an url-safe base64-encoded string into its bytes
    by first adding the stripped necessary padding characters.

    This is the way Telegram shares binary data as strings,
    such as Bot API-style file IDs or invite links.

    Returns `None` if the input string was not valid.
    """
    try:
        return base64.urlsafe_b64decode(string + '=' * (len(string) % 4))
    except (binascii.Error, ValueError, TypeError):
        return None  # not valid base64, not valid ascii, not a string 
Example 21
Project: Telethon   Author: LonamiWebs   File: string.py    License: MIT License 5 votes vote down vote up
def decode(x: str) -> bytes:
        return base64.urlsafe_b64decode(x) 
Example 22
Project: normandy   Author: mozilla   File: signing.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def verify_signature_pubkey(data, signature, pubkey):
    """
    Verify a signature.

    If the signature is valid, returns True. If the signature is invalid, raise
    an exception explaining why.
    """
    # Data must be encoded as bytes
    if isinstance(data, str):
        data = data.encode()

    # Content signature implicitly adds a prefix to signed data
    data = b"Content-Signature:\x00" + data

    # fastecdsa expects ASCII armored keys, but ours is unarmored. Add the
    # armor before passing the key to the library.
    EC_PUBLIC_HEADER = "-----BEGIN PUBLIC KEY-----"
    EC_PUBLIC_FOOTER = "-----END PUBLIC KEY-----"
    verifying_pubkey = PEMEncoder.decode_public_key(
        "\n".join([EC_PUBLIC_HEADER, pubkey, EC_PUBLIC_FOOTER])
    )

    try:
        signature = base64.urlsafe_b64decode(signature)
        signature = ecdsa.util.sigdecode_string(signature, order=ecdsa.curves.NIST384p.order)
    except binascii.Error as e:
        if BASE64_WRONG_LENGTH_RE.match(e.args[0]):
            raise WrongSignatureSize("Base64 encoded signature was not a multiple of 4")
        else:
            raise
    except ecdsa.util.MalformedSignature:
        raise WrongSignatureSize()

    verified = fastecdsa.ecdsa.verify(
        signature, data, verifying_pubkey, curve=fastecdsa.curve.P384, hashfunc=hashlib.sha384
    )

    if not verified:
        raise SignatureDoesNotMatch()

    return True 
Example 23
Project: cassh   Author: nbeguier   File: cassh_web.py    License: Apache License 2.0 5 votes vote down vote up
def self_decode(key, enc):
    dec = []
    # Try to use urlsafe_b64decode before encoding
    try:
        encoded = urlsafe_b64decode(enc).decode()
    except TypeError:
        encoded = urlsafe_b64decode(enc.encode())
    for i in range(len(encoded)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(encoded[i]) - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec) 
Example 24
Project: recruit   Author: Frank-qlu   File: encoding.py    License: Apache License 2.0 5 votes vote down vote up
def base64_decode(string):
    """Base64 decode a URL-safe string of bytes or text. The result is
    bytes.
    """
    string = want_bytes(string, encoding="ascii", errors="ignore")
    string += b"=" * (-len(string) % 4)

    try:
        return base64.urlsafe_b64decode(string)
    except (TypeError, ValueError):
        raise BadData("Invalid base64-encoded data")


# The alphabet used by base64.urlsafe_* 
Example 25
Project: browserscope   Author: elsigh   File: blob_upload_test.py    License: Apache License 2.0 5 votes vote down vote up
def check_key(self, blob_key, expected_time, expected_random):
    """Check that blob_key decodes to expected value.

    Args:
      blob_key: Blob key that was actually generated.
      expected_time: Time stamp that is expected to be in the md5 digest.
      expected_random: Random number that is expected to be in the md5 digest.
    """
    if blob_key is None:
      self.fail('Generated blob-key is None.')
    digester = hashlib.md5()
    digester.update(str(expected_time))
    digester.update(str(expected_random))
    actual_digest = base64.urlsafe_b64decode(blob_key)
    self.assertEquals(digester.digest(), actual_digest) 
Example 26
Project: iris-relay   Author: linkedin   File: gmail.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process_message(message):
    """Process message to yield body and sender.

    :param message:
    :return: message body and sender
    :rtype: tuple(str, str)
    """
    payload = message.get('payload', {})
    headers = payload.get('headers', [])
    if 'data' in payload.get('body', {}):
        parts = [payload]
    else:
        parts = payload.get('parts', [])

    for part in parts:
        # TODO(khrichar): support other content types
        mime_type = part.get('mimeType')
        if mime_type == 'text/plain':
            encoded_content = part.get('body', {}).get('data', '')
            content = urlsafe_b64decode(encoded_content)
            yield headers, content
        elif mime_type == 'text/html':
            logger.debug('ignore html mime type for message: %s', message)
        elif mime_type == 'multipart/alternative':
            fake_message = {
                'payload': {
                    'parts': part.get('parts', []),
                    'headers': part.get('headers', {}),
                }
            }
            for h, c in process_message(fake_message):
                yield h, c
        else:
            logger.info('skip parsing mime type %s for message: %s', mime_type, message) 
Example 27
Project: iris-relay   Author: linkedin   File: gmail.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_mime_message(
            self,
            msg_id,
            user_id='me'):
        """Get a Message and use it to create a MIME Message.

        :param msg_id: The ID of the Message required.
        :param user_id: User's email address. The special value "me"
            can be used to indicate the authenticated user.
        :return: A MIME Message, consisting of data from Message.
        :rtype: :class:`email.message.Message`
        """
        self.connect()
        ret = None
        try:
            message = self.client.users().messages().get(
                userId=user_id,
                id=msg_id,
                format='raw'
            ).execute()
        except (socks.HTTPError, errors.HttpError) as error:
            logger.error('An error occurred: %s', error)
        else:
            logger.info('Message snippet: %s', message.get('snippet', ''))
            msg_str = urlsafe_b64decode(message.get('raw', '').encode('ASCII'))
            ret = message_from_string(msg_str)
        return ret 
Example 28
Project: iris-relay   Author: linkedin   File: gmail.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse_gmail_push_data(data):
        notification = loads(urlsafe_b64decode(str(data)))
        return notification.get('emailAddress'), notification.get('historyId') 
Example 29
Project: endpoints-python   Author: cloudendpoints   File: users_id_token.py    License: Apache License 2.0 5 votes vote down vote up
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 30
Project: bambleweeny   Author: u1i   File: bambleweeny.py    License: MIT License 5 votes vote down vote up
def _b64_dec(s):
	return(base64.urlsafe_b64decode(s))