Python base64.urlsafe_b64encode() Examples
The following are 30
code examples of base64.urlsafe_b64encode().
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 iris-relay with BSD 2-Clause "Simplified" License | 6 votes |
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 #2
Source File: client.py From iris-relay with BSD 2-Clause "Simplified" License | 6 votes |
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 #3
Source File: blob_download_test.py From browserscope with Apache License 2.0 | 6 votes |
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 #4
Source File: blob_upload_test.py From browserscope with Apache License 2.0 | 6 votes |
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 #5
Source File: wheel.py From dephell with MIT License | 6 votes |
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 #6
Source File: qutescheme.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
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 #7
Source File: utils.py From normandy with Mozilla Public License 2.0 | 6 votes |
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 #8
Source File: pyoidc_facade.py From Flask-pyoidc with Apache License 2.0 | 6 votes |
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 #9
Source File: crypt.py From pgrepup with GNU General Public License v3.0 | 6 votes |
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 #10
Source File: avatarwindow.py From Tkinter-GUI-Programming-by-Example with MIT License | 6 votes |
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 #11
Source File: bambleweeny.py From bambleweeny with MIT License | 5 votes |
def _b64_enc(s): return(base64.urlsafe_b64encode(s))
Example #12
Source File: signing.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def b64_encode(s): return base64.urlsafe_b64encode(s).strip(b'=')
Example #13
Source File: bambleweeny.py From bambleweeny with MIT License | 5 votes |
def _get_token_data(token): token_data = {} token_data["error"] = "0" token_data["admin"] = "False" token_data["authenticated"] = "False" try: # Get base64 encoded content and the signature from the token separator = token.find(".") sig_token = token[separator+1:] content_raw = _b64_dec(token[:separator]) content = json.loads(content_raw) # Create signature c = base64.urlsafe_b64encode(json.dumps(content)) hmac1 = hmac.new(salt, c, hashlib.sha256 ) sig_check = hmac1.hexdigest()[:8] # Only get the data if the signature is valid if sig_token == sig_check: token_data["timestamp"] = int(content["t"]) token_data["user"] = content["u"] token_data["id"] = content["i"] token_data["cluster_id"] = content["c"] if content["u"] == 'admin': token_data["admin"] = "True" else: token_data["error"] = "1" except: token_data["error"] = "1" return(token_data)
Example #14
Source File: file_decryptor.py From caldera with Apache License 2.0 | 5 votes |
def get_encryptor(salt, key): generated_key = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=bytes(salt, 'utf-8'), iterations=2 ** 20, backend=default_backend()) return Fernet(base64.urlsafe_b64encode(generated_key.derive(bytes(key, 'utf-8'))))
Example #15
Source File: file_svc.py From caldera with Apache License 2.0 | 5 votes |
def _get_encryptor(self): generated_key = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=bytes(self.get_config('crypt_salt'), 'utf-8'), iterations=2 ** 20, backend=default_backend()) return Fernet(base64.urlsafe_b64encode(generated_key.derive(bytes(self.get_config('encryption_key'), 'utf-8'))))
Example #16
Source File: wheel.py From jbox with MIT License | 5 votes |
def rehash(path, algo='sha256', blocksize=1 << 20): """Return (hash, length) for path using hashlib.new(algo)""" h = hashlib.new(algo) length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize): length += len(block) h.update(block) digest = 'sha256=' + urlsafe_b64encode( h.digest() ).decode('latin1').rstrip('=') return (digest, length)
Example #17
Source File: wheel.py From jbox with MIT License | 5 votes |
def get_hash(self, data, hash_kind=None): if hash_kind is None: hash_kind = self.hash_kind try: hasher = getattr(hashlib, hash_kind) except AttributeError: raise DistlibException('Unsupported hash algorithm: %r' % hash_kind) result = hasher(data).digest() result = base64.urlsafe_b64encode(result).rstrip(b'=').decode('ascii') return hash_kind, result
Example #18
Source File: service_account.py From earthengine with MIT License | 5 votes |
def _urlsafe_b64encode(data): return base64.urlsafe_b64encode( json.dumps(data, separators=(',', ':')).encode('UTF-8')).rstrip('=')
Example #19
Source File: http.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def urlsafe_base64_encode(s): """ Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b'\n=')
Example #20
Source File: crypt.py From earthengine with MIT License | 5 votes |
def _urlsafe_b64encode(raw_bytes): return base64.urlsafe_b64encode(raw_bytes).rstrip('=')
Example #21
Source File: users_id_token_test.py From endpoints-python with Apache License 2.0 | 5 votes |
def testErrorStringLoggableBadBody(self): """Check that the Unparseable Body error is loggable.""" token_body = 'bad utf-8 \xff' token_parts = self._SAMPLE_TOKEN.split('.') token = '.'.join([token_parts[0], base64.urlsafe_b64encode(token_body), token_parts[2]]) self.CheckErrorLoggable(token)
Example #22
Source File: users_id_token_test.py From endpoints-python with Apache License 2.0 | 5 votes |
def testErrorStringLoggableBadHeader(self): """Check that the Bad Header error is loggable.""" token_part = 'bad utf-8 \xff' token = '.'.join([base64.urlsafe_b64encode(token_part)] * 3) self.CheckErrorLoggable(token)
Example #23
Source File: test_oidc.py From openeo-python-client with Apache License 2.0 | 5 votes |
def _jwt_encode(header: dict, payload: dict, signature="s1gn6tur3"): """Poor man's JWT encoding (just for unit testing purposes)""" def encode(d): return base64.urlsafe_b64encode(json.dumps(d).encode("ascii")).decode("ascii").replace('=', '') return ".".join([encode(header), encode(payload), signature])
Example #24
Source File: users_id_token_test.py From endpoints-python with Apache License 2.0 | 5 votes |
def testInvalidSignature(self): """Verify that a body that doesn't match the signature fails.""" body = self.GetSampleBody() # Modify the issued and expiration times. body['iat'] += 60 body['exp'] += 60 encoded_body = base64.urlsafe_b64encode(json.dumps(body)) split_token = self._SAMPLE_TOKEN.split('.') token = '.'.join((split_token[0], encoded_body, split_token[2])) self.assertRaises(users_id_token._AppIdentityError, users_id_token._verify_signed_jwt_with_certs, token, self._SAMPLE_TIME_NOW, self.cache)
Example #25
Source File: schort.py From schort with Creative Commons Zero v1.0 Universal | 5 votes |
def insertIdUnique(longUrl, idToCheck=None): hashUrl = hashlib.sha256(longUrl.encode()).digest() base64Url = base64.urlsafe_b64encode(hashUrl).decode() if idToCheck == None or idToCheck == "": idToCheck = base64Url[:4] conn = sqlite3.connect("data/links.sqlite") c = conn.cursor() try: c.execute('INSERT INTO links VALUES (?, ?, ?, ?, ?)', (idToCheck, longUrl, int(time.time()), request.remote_addr, "default" )) databaseId = idToCheck conn.commit() conn.close() except sqlite3.IntegrityError as e: print("Hash already exists, does the long URL matches?") longUrlDb = c.execute('SELECT * FROM links WHERE shortLink=?', (idToCheck, )).fetchone() if longUrl == longUrlDb[1]: print(longUrl + " is already in database with id " + idToCheck + ". Serving old id…") databaseId = idToCheck else: print("Found real hash collision for " + longUrl + " and " + longUrlDb[1]) conn.commit() conn.close() if len(base64Url) - 1 >= len(idToCheck) + 1: databaseId = insertIdUnique(longUrl, idToCheck=base64Url[:len(idToCheck)+1]) else: print("Can't produce a long enough hash from the new link to be unique. This should never happen") print("Bailing out, you are on your own. Good luck.") print("=========================================================================================") abort(500) return databaseId
Example #26
Source File: test_im_logic.py From im with GNU General Public License v3.0 | 5 votes |
def gen_token(self, aud=None, exp=None): data = { "sub": "user_sub", "iss": "https://iam-test.indigo-datacloud.eu/", "exp": 1465471354, "iat": 1465467755, "jti": "jti", } if aud: data["aud"] = aud if exp: data["exp"] = int(time.time()) + exp return ("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.%s.ignored" % base64.urlsafe_b64encode(json.dumps(data).encode("utf-8")).decode("utf-8"))
Example #27
Source File: test_gmail.py From iris-relay with BSD 2-Clause "Simplified" License | 5 votes |
def test_process_message_multipart(): fake_headers = [{ 'name': 'Content-Type', 'value': 'multipart/alternative; boundary="===============3481026495533768394=="' }] fake_content = 'hello' fake_content = fake_content.encode('utf8') fake_message = { 'payload': { 'headers': fake_headers, 'mimeType': 'multipart/related', 'parts': [{ 'headers': fake_headers, 'mimeType': 'multipart/alternative', 'parts': [ { 'mimeType': 'text/plain', 'body': {'data': urlsafe_b64encode(fake_content)} } ] }] } } is_message_processed = False for headers, content in process_message(fake_message): is_message_processed = True assert headers == fake_headers assert content == fake_content assert is_message_processed
Example #28
Source File: test_gmail.py From iris-relay with BSD 2-Clause "Simplified" License | 5 votes |
def test_process_message_text_plain(): fake_headers = [{'name': 'Content-Type', 'value': 'text/plain; charset="us-ascii"'}] fake_content = 'hello' fake_content = fake_content.encode('utf8') fake_message = {'payload': { 'headers': fake_headers, 'parts': [{'mimeType': 'text/plain', 'body': {'data': urlsafe_b64encode(fake_content)}}] }} is_message_processed = False for headers, content in process_message(fake_message): is_message_processed = True assert headers == fake_headers assert content == fake_content assert is_message_processed
Example #29
Source File: __init__.py From pywarp with Apache License 2.0 | 5 votes |
def b64url_encode(b): return base64.urlsafe_b64encode(b).decode()
Example #30
Source File: util.py From jbox with MIT License | 5 votes |
def urlsafe_b64encode(data): """urlsafe_b64encode without padding""" return base64.urlsafe_b64encode(data).rstrip(binary('='))