Python base64.urlsafe_b64encode() Examples

The following are 30 code examples for showing how to use base64.urlsafe_b64encode(). 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: Flask-pyoidc   Author: zamzterz   File: pyoidc_facade.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, method, request):
        """
        Args:
            method (str): Client Authentication Method. Only 'client_secret_basic' and 'client_secret_post' is
                supported.
            request (MutableMapping[str, str]): Token request parameters. This may be modified, i.e. if
                'client_secret_post' is used the client credentials will be added.

        Returns:
            (Mapping[str, str]): HTTP headers to be included in the token request, or `None` if no extra HTTPS headers
            are required for the token request.
        """
        if method == 'client_secret_post':
            request['client_id'] = self._client_id
            request['client_secret'] = self._client_secret
            return None  # authentication is in the request body, so no Authorization header is returned

        # default to 'client_secret_basic'
        credentials = '{}:{}'.format(self._client_id, self._client_secret)
        basic_auth = 'Basic {}'.format(base64.urlsafe_b64encode(credentials.encode('utf-8')).decode('utf-8'))
        return {'Authorization': basic_auth} 
Example 2
Project: pgrepup   Author: rtshome   File: crypt.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _get_key():
    if this.key:
        return this.key

    secret = getpass.getpass()
    try:
        salt = config().get('Security', 'salt')
    except NoOptionError:
        salt = base64.urlsafe_b64encode(os.urandom(16))
        config().set('Security', 'salt', salt)

    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    this.key = base64.urlsafe_b64encode(kdf.derive(secret))
    return this.key 
Example 3
Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: avatarwindow.py    License: MIT License 6 votes vote down vote up
def choose_image(self):
        image_file = filedialog.askopenfilename(filetypes=self.image_file_types)

        if image_file:
            avatar = Image.open(image_file)
            avatar.thumbnail((128, 128))
            avatar.save(avatar_file_path, "PNG")

            img_contents = ""
            img_b64 = ""
            with open(avatar_file_path, "rb") as img:
                img_contents = img.read()
                img_b64 = base64.urlsafe_b64encode(img_contents)

            self.master.requester.update_avatar(self.master.username, img_b64)

            self.current_avatar_image = tk.PhotoImage(file=avatar_file_path)
            self.current_avatar.configure(image=self.current_avatar_image) 
Example 4
Project: qutebrowser   Author: qutebrowser   File: qutescheme.py    License: GNU General Public License v3.0 6 votes vote down vote up
def qute_settings(url: QUrl) -> _HandlerRet:
    """Handler for qute://settings. View/change qute configuration."""
    global csrf_token

    if url.path() == '/set':
        if url.password() != csrf_token:
            message.error("Invalid CSRF token for qute://settings!")
            raise RequestDeniedError("Invalid CSRF token!")
        return _qute_settings_set(url)

    # Requests to qute://settings/set should only be allowed from
    # qute://settings. As an additional security precaution, we generate a CSRF
    # token to use here.
    if secrets:
        csrf_token = secrets.token_urlsafe()
    else:
        # On Python < 3.6, from secrets.py
        token = base64.urlsafe_b64encode(os.urandom(32))
        csrf_token = token.rstrip(b'=').decode('ascii')

    src = jinja.render('settings.html', title='settings',
                       configdata=configdata,
                       confget=config.instance.get_str,
                       csrf_token=csrf_token)
    return 'text/html', src 
Example 5
Project: normandy   Author: mozilla   File: utils.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def sri_hash(data, url_safe=False):
    """
    Return a subresource integrity attribute string for a file
    containing the given binary data.

    SRI attributes are a string of the form "{algorithm}-{hash}", where
    {algorithm} is the hash algorithm, and {hash} is a base64-encoded
    hash of the data using the specified algorithm.

    :param data:
        Bytes-like object containing the data to hash.
    """
    digest = sha384(data).digest()
    if url_safe:
        data_hash = urlsafe_b64encode(digest)
    else:
        data_hash = b64encode(digest)
    return "sha384-" + data_hash.decode() 
Example 6
Project: dephell   Author: dephell   File: wheel.py    License: MIT License 6 votes vote down vote up
def _write_file(self, archive, path: str, fpath: Path) -> None:
        # write content into archive
        archive.write(filename=str(fpath), arcname=path, compress_type=ZIP_DEFLATED)

        # calculate hashsum
        # https://stackoverflow.com/questions/22058048/hashing-a-file-in-python
        digest = sha256()
        with fpath.open('rb') as stream:
            while True:
                data = stream.read(65536)
                if not data:
                    break
                digest.update(data)
        digest = urlsafe_b64encode(digest.digest()).decode().rstrip('=')

        self._records.append((path, digest, fpath.stat().st_size)) 
Example 7
Project: browserscope   Author: elsigh   File: blob_upload_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_base64(self):
    """Test automatic decoding of a base-64-encoded message."""
    # Create upload.
    upload_data = (
        """--================1234==
Content-Type: text/plain
MIME-Version: 1.0
Content-Disposition: form-data; name="field1"; filename="stuff.txt"
Content-Transfer-Encoding: base64

%s
--================1234==--""" % base64.urlsafe_b64encode('value'))

    upload_url = blobstore.create_upload_url('/success')

    upload, forward_environ, _ = self._run_test_success(
        upload_data, upload_url)

    self.assertEquals('/success', forward_environ['PATH_INFO'])
    self.assertEquals(
        ('form-data', {'filename': 'stuff.txt', 'name': 'field1'}),
        cgi.parse_header(upload['content-disposition'])) 
Example 8
Project: browserscope   Author: elsigh   File: blob_download_test.py    License: Apache License 2.0 6 votes vote down vote up
def create_blob(self):
    """Create a GS object in the datastore and on disk.

    Overrides the superclass create_blob method.

    Returns:
      The BlobKey of the new object."
    """
    data = 'a blob'
    filename = '/gs/some_bucket/some_object'
    blob_store_key = base64.urlsafe_b64encode(filename)
    self.blob_storage.StoreBlob(blob_store_key, cStringIO.StringIO(data))

    blob_key = blobstore.create_gs_key(filename)
    entity = datastore.Entity(file_service_stub.GS_INFO_KIND,
                              name=blob_key,
                              namespace='')
    entity['content_type'] = 'image/png'
    entity['filename'] = 'largeblob.png'
    entity['size'] = len(data)
    entity['storage_key'] = blob_store_key
    datastore.Put(entity)

    return blob_key 
Example 9
Project: iris-relay   Author: linkedin   File: client.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def post(self, endpoint, data, params=None, raw=False, headers=None):
        HMAC = self.HMAC.copy()
        path = self.base_path + endpoint
        method = 'POST'
        hdrs = {}
        window = int(time.time()) // 5
        if not raw:
            hdrs = {'Content-Type': 'application/json'}
            body = json.dumps(data)
        else:
            hdrs = headers if headers else {}
            body = data

        if params:
            path = ''.join([path, '?', urlencode(params)])
        text = '%s %s %s %s' % (window, method, path, body)
        text = text.encode('utf8')
        HMAC.update(text)
        digest = base64.urlsafe_b64encode(HMAC.digest())

        auth_header = 'hmac %s:' % self.user
        hdrs['Authorization'] = auth_header.encode('utf8') + digest

        return self.urlopen(method, path, headers=hdrs, body=body) 
Example 10
Project: iris-relay   Author: linkedin   File: client.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get(self, endpoint, params=None, raw=False):
        HMAC = self.HMAC.copy()
        path = self.base_path + endpoint
        method = 'GET'
        window = int(time.time()) // 5
        body = ''
        if params:
            path = ''.join([path, '?', urlencode(params)])
        text = '%s %s %s %s' % (window, method, path, body)
        text = text.encode('utf8')
        HMAC.update(text)
        digest = base64.urlsafe_b64encode(HMAC.digest())

        auth_header = 'hmac %s:' % self.user
        headers = {
            'Content-Type': 'application/json',
            'Authorization': auth_header.encode('utf8') + digest
        }
        return self.urlopen(method, path, headers=headers) 
Example 11
Project: pywarp   Author: pyauth   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def b64url_encode(b):
    return base64.urlsafe_b64encode(b).decode() 
Example 12
Project: Flask-pyoidc   Author: zamzterz   File: test_pyoidc_facade.py    License: Apache License 2.0 5 votes vote down vote up
def basic_auth(self):
        credentials = '{}:{}'.format(self.CLIENT_ID, self.CLIENT_SECRET)
        return 'Basic {}'.format(base64.urlsafe_b64encode(credentials.encode('utf-8')).decode('utf-8')) 
Example 13
Project: zmirror   Author: aploium   File: utils.py    License: MIT License 5 votes vote down vote up
def embed_real_url_to_embedded_url(real_url_raw, url_mime, escape_slash=False):
    """
    将url的参数(?q=some&foo=bar)编码到url路径中, 并在url末添加一个文件扩展名
    在某些对url参数支持不好的CDN中, 可以减少错误
    `cdn_redirect_encode_query_str_into_url`设置依赖于本函数, 详细说明可以看配置文件中的对应部分
    解码由 extract_real_url_from_embedded_url() 函数进行, 对应的例子也请看这个函数
    :rtype: str
    """
    # dbgprint(real_url_raw, url_mime, escape_slash)
    if escape_slash:
        real_url = real_url_raw.replace(r'\/', '/')
    else:
        real_url = real_url_raw
    url_sp = urlsplit(real_url)
    if not url_sp.query:  # no query, needn't rewrite
        return real_url_raw

    byte_query = url_sp.query.encode()
    if len(byte_query) > 128:  # 当查询参数太长时, 进行gzip压缩
        gzip_label = 'z'  # 进行压缩后的参数, 会在标识区中添加一个z
        byte_query = zlib.compress(byte_query)
    else:
        gzip_label = ''

    b64_query = base64.urlsafe_b64encode(byte_query).decode()
    # dbgprint(url_mime)
    mixed_path = url_sp.path + '_' + _url_salt + gzip_label + '_.' \
                 + b64_query \
                 + '._' + _url_salt + '_.' + mime_to_use_cdn[url_mime]
    result = urlunsplit((url_sp.scheme, url_sp.netloc, mixed_path, '', ''))

    if escape_slash:
        result = s_esc(result)
        # dbgprint('embed:', real_url_raw, 'to:', result)
    return result 
Example 14
Project: zmirror   Author: aploium   File: zmirror.py    License: MIT License 5 votes vote down vote up
def filter_client_request():
    """过滤用户请求, 视情况拒绝用户的访问
    :rtype: Union[Response, None]
    """
    dbgprint('Client Request Url: ', request.url)

    # crossdomain.xml
    if os.path.basename(request.path) == 'crossdomain.xml':
        dbgprint('crossdomain.xml hit from', request.url)
        return crossdomain_xml()

    # Global whitelist ua
    if check_global_ua_pass(str(request.user_agent)):
        return None

    if is_deny_spiders_by_403 and is_denied_because_of_spider(str(request.user_agent)):
        return generate_simple_resp_page(b'Spiders Are Not Allowed To This Site', 403)

    if human_ip_verification_enabled and (
                ((human_ip_verification_whitelist_from_cookies or enable_custom_access_cookie_generate_and_verify)
                 and must_verify_cookies)
            or is_ip_not_in_allow_range(request.remote_addr)
    ):
        dbgprint('ip', request.remote_addr, 'is verifying cookies')
        if 'zmirror_verify' in request.cookies and \
                ((human_ip_verification_whitelist_from_cookies and verify_ip_hash_cookie(request.cookies.get('zmirror_verify')))
                 or (enable_custom_access_cookie_generate_and_verify and custom_verify_access_cookie(
                        request.cookies.get('zmirror_verify'), request))):
            ip_whitelist_add(request.remote_addr, info_record_dict=request.cookies.get('zmirror_verify'))
            dbgprint('add to ip_whitelist because cookies:', request.remote_addr)
        else:
            return redirect(
                "/ip_ban_verify_page?origin=" + base64.urlsafe_b64encode(str(request.url).encode(encoding='utf-8')).decode(
                    encoding='utf-8'),
                code=302)

    return None 
Example 15
Project: pywren-ibm-cloud   Author: pywren   File: infinispan.py    License: Apache License 2.0 5 votes vote down vote up
def __key_url(self, key):
        urlSafeEncodedBytes = base64.urlsafe_b64encode(key.encode("utf-8"))
        urlSafeEncodedStr = str(urlSafeEncodedBytes, "utf-8")
        url = self.endpoint + '/rest/v2/caches/' + self.cache_name + '/' + urlSafeEncodedStr
        return url 
Example 16
Project: endpoints-tools   Author: cloudendpoints   File: generate-google-id-jwt.py    License: Apache License 2.0 5 votes vote down vote up
def generate_jwt(args):
    """Generates a signed JSON Web Token using a service account. Based on https://cloud.google.com/endpoints/docs/service-to-service-auth"""
    # Make sure the service account has "Service Account Token Creator" permissions in Google IAM
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
      args.service_account_file).create_scoped(['https://www.googleapis.com/auth/cloud-platform'])

    service = googleapiclient.discovery.build(
        serviceName='iam', version='v1', credentials=credentials)

    now = int(time.time())
    header_json = json.dumps({
        "typ": "JWT",
        "alg": "RS256"})

    payload_json = json.dumps({
        'iat': now,
        "exp": now + 3600,
        'iss': args.issuer if args.issuer else credentials.service_account_email,
        "target_audience": 'https://' + args.aud,
        "aud": "https://www.googleapis.com/oauth2/v4/token"
    })

    header_and_payload = '{}.{}'.format(
        base64.urlsafe_b64encode(header_json),
        base64.urlsafe_b64encode(payload_json))
    slist = service.projects().serviceAccounts().signBlob(
        name="projects/-/serviceAccounts/" + credentials.service_account_email,
        body={'bytesToSign': base64.b64encode(header_and_payload)})
    res = slist.execute()
    signature = base64.urlsafe_b64encode(
        base64.decodestring(res['signature']))
    signed_jwt = '{}.{}'.format(header_and_payload, signature)

    return signed_jwt 
Example 17
Project: shhh   Author: smallwat3r   File: utils.py    License: MIT License 5 votes vote down vote up
def __derive_key(self, salt: bytes, iterations: int) -> bytes:
        """Derive a secret key from a given passphrase and salt."""
        kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                         length=32,
                         salt=salt,
                         iterations=iterations,
                         backend=default_backend())
        return urlsafe_b64encode(kdf.derive(self.passphrase.encode())) 
Example 18
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 19
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 20
Project: razzy-spinner   Author: rafasashi   File: wordnet_app.py    License: GNU General Public License v3.0 5 votes vote down vote up
def encode(self):
        """
        Encode this reference into a string to be used in a URL.
        """
        # This uses a tuple rather than an object since the python
        # pickle representation is much smaller and there is no need
        # to represent the complete object.
        string = pickle.dumps((self.word, self.synset_relations), -1)
        return base64.urlsafe_b64encode(string).decode() 
Example 21
Project: gist-alfred   Author: danielecook   File: utils.py    License: MIT License 5 votes vote down vote up
def base64url_encode(input):
    return base64.urlsafe_b64encode(input).replace(b'=', b'') 
Example 22
Project: Telethon   Author: LonamiWebs   File: utils.py    License: MIT License 5 votes vote down vote up
def _encode_telegram_base64(string):
    """
    Inverse for `_decode_telegram_base64`.
    """
    try:
        return base64.urlsafe_b64encode(string).rstrip(b'=').decode('ascii')
    except (binascii.Error, ValueError, TypeError):
        return None  # not valid base64, not valid ascii, not a string 
Example 23
Project: Telethon   Author: LonamiWebs   File: string.py    License: MIT License 5 votes vote down vote up
def encode(x: bytes) -> str:
        return base64.urlsafe_b64encode(x).decode('ascii') 
Example 24
Project: threat_intel   Author: Yelp   File: http.py    License: MIT License 5 votes vote down vote up
def _handle_file_download(self, response):
        name = None
        data = None
        try:
            name = re.findall('filename=(.+)', response.headers['content-disposition'])[0]
            data = urlsafe_b64encode(response.text.encode('utf-8')).decode('utf-8')
        except Exception:
            logging.exception('Unable to extract download data for {} '.format(response.request.url))
        return {'data': {'id': name, 'text': data}} 
Example 25
Project: app   Author: simple-login   File: jose_utils.py    License: MIT License 5 votes vote down vote up
def id_token_hash(value, hashfunc=hashlib.sha256):
    """
    Inspired from oauthlib
    """
    digest = hashfunc(value.encode()).digest()
    left_most = len(digest) // 2
    return base64.urlsafe_b64encode(digest[:left_most]).decode().rstrip("=") 
Example 26
Project: hyperledger-py   Author: yeasy   File: auth.py    License: Apache License 2.0 5 votes vote down vote up
def encode_header(auth):
    auth_json = json.dumps(auth).encode('ascii')
    return base64.urlsafe_b64encode(auth_json) 
Example 27
Project: bugbuzz-python   Author: fangpenlin   File: __init__.py    License: MIT License 5 votes vote down vote up
def _pam_sign(self, msg):

        return urlsafe_b64encode(hmac.new(
            self.secret_key.encode("utf-8"),
            msg.encode("utf-8"),
            sha256
        ).digest()) 
Example 28
Project: bugbuzz-python   Author: fangpenlin   File: __init__.py    License: MIT License 5 votes vote down vote up
def _pam_sign(self, msg):

        return urlsafe_b64encode(hmac.new(
            self.secret_key.encode("utf-8"),
            msg.encode("utf-8"),
            sha256
        ).digest()) 
Example 29
Project: dataiku-contrib   Author: dataiku   File: connector.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, config):
        Connector.__init__(self, config)

        self.api_key = str(self.config.get("api_key"))
        self.location = str(self.config.get("location"))
        self.from_date = str(self.config.get("from_date"))
        self.to_date = str(self.config.get("to_date"))
        self.calls_per_minute = int(self.config.get("calls_per_minute"))
        self.api_limit = int(self.config.get("api_limit", 500))
        self.cache_folder = str(self.config.get("cache_folder", "/tmp/dss-plugin-wunderground"))

        # Cache file path
        filename = "cache-wunderground-history-%s.json" % base64.urlsafe_b64encode(self.location)
        self.cache_file = os.path.join(self.cache_folder, filename)
        print  "Wunderground plugin - Cache file: %s" % self.cache_file

        # Cache directory
        if not os.path.isdir(self.cache_folder):
            os.makedirs(self.cache_folder)

        # Create cache file if does not exist
        if not os.path.exists(self.cache_file):
            with open(self.cache_file, 'w') as f:
                json.dump({}, f)
                f.close()

        # Limit on the number of API calls. At each sample refresh, set to 0 again!
        self.api_calls = 0 
Example 30
Project: dataiku-contrib   Author: dataiku   File: connector.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, config):
        Connector.__init__(self, config)

        self.api_key = str(self.config.get("api_key"))
        self.latitude = str(self.config.get("latitude"))
        self.longitude = str(self.config.get("longitude"))
        self.from_date = str(self.config.get("from_date"))
        self.to_date = str(self.config.get("to_date"))
        self.cache_folder = str(self.config.get("cache_folder", ""))
        self.api_limit = int(self.config.get("api_limit", -1))
        self.cache_data = {}

        # Cache file
        if self.cache_folder != "":

            name = str(self.latitude) + '-' + str(self.longitude)
            filename = "cache-forecastio-history-%s.json" % base64.urlsafe_b64encode(name.encode())
            self.cache_file = os.path.join(self.cache_folder, filename)

            # create directory if required
            if not os.path.isdir(self.cache_folder):
                os.makedirs(self.cache_folder)

            # create file if required
            if not os.path.exists(self.cache_file):
                with open(self.cache_file, 'w') as f:
                    json.dump({}, f)
                    f.close()
        else:
            self.cache_folder = None
            self.cache_file = None

        # The API returns the number of call made for today. We keep it to optionnaly limit the number of calls.
        # For te first call, we don't know the actual value but we assume it is 0.
        self.api_calls = 0