def ungz(*args): """ .. function:: ungz(blob) -> text Function *ungz* decompresses gzip blobs. If the input blobs aren't gzip compressed, then it just returns them as they are. Examples: >>> table1(''' ... "qwerqwerqwer" ... "asdfasdfasdf" ... ''') >>> sql("select ungz(gz(a)) from table1") ungz(gz(a)) ------------ qwerqwerqwer asdfasdfasdf >>> sql("select ungz('string'), ungz(123)") ungz('string') | ungz(123) -------------------------- string | 123 """ try: return zlib.decompress(args[0]) except KeyboardInterrupt: raise except: return args[0]
def run(self, **kwargs): self.kwargs = kwargs try: key_id = self.kwargs['key_id'] if self.kwargs['data'].startswith('@'): path = self.kwargs['data'][1:] try: with open(path, 'rb') as fh: data = fh.read(-1) except Exception as ex: self.log.exception( 'Failed loading data from file: {}'.format(ex)) return else: data = kwargs['data'] session = get_local_aws_session() if session.get_credentials().method != 'iam-role': kms_account_name = app_config.kms_account_name if not kms_account_name: print( 'you must set the kms_account_name setting in your configuration file to the name of the ' 'account that is able to decrypt the user data') return acct = Account.get(kms_account_name) if not acct: print( 'You must add the {} account to the system for this to work' .format(kms_account_name)) return session = get_aws_session(acct) kms = session.client('kms', region_name=self.dbconfig.get( 'region', self.ns, 'us-west-2')) if kwargs['mode'] == 'encrypt': if not kwargs['key_id']: print( 'You must provide a key id to use for encryption to work' ) return compressed = zlib.compress( bytes(json.dumps(json.loads(data)), 'utf-8')) res = kms.encrypt(KeyId=key_id, Plaintext=compressed) self.output(res['CiphertextBlob']) else: res = kms.decrypt(CiphertextBlob=b64decode(data)) self.output( json.dumps(json.loads( str(zlib.decompress(res['Plaintext']), 'utf-8')), indent=4)) except Exception: self.log.exception( 'An error occured while doing userdata.py stuff')
def run(self): sock = self.create_socket() connection, client_address = sock.accept() plt.ion() plt.axis('off') while True: stream_buffer = '' try: while True: try: received_data = connection.recv(self.packet_size) stream_buffer += received_data if len(received_data) < self.packet_size: # Decompress received data stream_buffer=zlib.decompress(stream_buffer) image = Image.open(io.BytesIO(stream_buffer)) display = plt.imshow(image, interpolation='nearest', aspect='auto') plt.pause(0.1) stream_buffer = '' time.sleep(0.1) except: print "[!] Failed to Render screenshot" except socket_error as e: print 'Error encountered.\n{}\nExiting..'.format(e) sock.close() exit(1) finally: sock.close()
def _generic_unserialize(cls, s, cls_assert=None): """Unserialize the given string serialized using _generic_serialize""" if s[0] == "P": data = s[1:] else: data = zlib.decompress(s) obj = loads(data) assert cls_assert is None or isinstance(obj, cls_assert), "Invalid %s representation" % cls_assert.__name__ return obj
def zlib_decompress(args): startAddr = int(args[1], 0) if len(args) > 1 else None endAddr = int(args[2], 0) if len(args) > 2 else None inFile = open(args[0], 'rb').read() decompressedData = zlib.decompress(inFile[startAddr:endAddr]) outFile = open(args[0] + ".decomp", 'wb') outFile.write(decompressedData) outFile.close()
def _decrypt_userdata(ciphertext, secret): ciphertext = base64.b64decode(ciphertext) iv, salt, ciphertext = ( ciphertext[:16], ciphertext[16:48], ciphertext[48:]) hmacKey, encKey, salt = _derive_keys(secret, salt) # decrypt try: ret = zlib.decompress(_decipher( ciphertext, encKey, iv, algorithms.AES)) except (zlib.error, ValueError) as e: raise DecryptionError(str(e)) # Check MAC mac = ret[-64:] ret = ret[:-64] if hmac.new(hmacKey, ret + iv + salt, hashlib.sha256).hexdigest() != mac.decode(): raise DecryptionError('HMAC does not match') return ret
def loads(cls, string): try: s = zlib.decompress(string) except: s = string return loads(s)
RoleSessionName='cloud_inquisitor') kms = boto3.session.Session( audit_role['Credentials']['AccessKeyId'], audit_role['Credentials']['SecretAccessKey'], audit_role['Credentials']['SessionToken'], ).client('kms', region_name=kms_region) else: kms = boto3.session.Session().client('kms', region_name=kms_region) user_data_url = app.config.get('USER_DATA_URL') res = requests.get(user_data_url) if res.status_code == 200: data = kms.decrypt(CiphertextBlob=b64decode(res.content)) kms_config = json.loads( zlib.decompress(data['Plaintext']).decode('utf-8')) app.config['SQLALCHEMY_DATABASE_URI'] = kms_config['db_uri'] else: print(res.status_code) raise RuntimeError('Failed loading user-data, cannot continue') db = SQLAlchemy(app) api = Api(app) # Must be imported after we initialized the db instance from cloud_inquisitor.config import dbconfig, DBConfig, DBCChoice from cloud_inquisitor.constants import ROLE_ADMIN, ROLE_USER, NS_AUTH from cloud_inquisitor.plugins.views import BaseView, LoginRedirectView, LogoutRedirectView from cloud_inquisitor.json_utils import InquisitorJSONDecoder, InquisitorJSONEncoder
#!/usr/bin/python3 from gzip import zlib import base64 #session = '.eJwlzzFuwzAMheG7aM4giiIlZS3QE3QXKIlsjbR1INtDEeTuddH9fcD_Hq7a1O3DXfd56MXVZbiryxLFLONgyMy-aelxIBsEGgHNBClp9A2CSOEWs8-cfNHUilAhBeBcEKT0MEC0l9OEUjwB5qBRm7XYQYwAJATruXWKUswKY-vm3cX1bVrd15t-nz2haU8RiAn_likapoToB3AAIvPsI54Rpxsyb3XTPnU_4X3p68vb62PZtyr1S-vPesxqn_JuOIgly_M0x6bz_zi65y9K1lC_.Xre0Sw.vp-YQMCaKuMS7PonrtNV8VZWu5s' print(zlib.decompress(base64.urlsafe_b64decode(session)))
"""Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!".""" from gzip import zlib as z strr = '"hello world!hello world!hello world!hello world!"' strr = strr.encode('utf-8') t = z.compress(strr, 1) print(t) t = z.decompress(t) print(t)