def __init__(self, stream, find_addr=None, output=None, key=None, hmac_out=False, full=False): self.stream = stream self.find_addr = find_addr self.print_next_payload = False self.decrypt_start = False self.output_file = output self.hmac_out = hmac_out self.full = full if key is not None: #self.cipher = AESCipher(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xaa\xaa\xbb\xbb\xcc\xcc\xdd\xdd') self.cipher = AESCipher( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' ) else: print("No Key Supplied, exitting") sys.exit(0) if output is not None: try: if os.path.getsize(output): open(output, "w").close() except: open(output, "a").close()
def get_credentials(url: str, credential_source: str) -> str: rsa = OAEP() key = rand_string() encrypted_key = rsa.encrypt(key,public_key) crypto = AESCipher(key) intervals = construct_tuples(MAX_SNIPPETS, MAX_SIZE) hashval = generate_hashval(intervals, entropy_data, MAX_SIZE) interval_payload = { 'hashval': hashval, 'intervals': intervals, 'credential_source': credential_source } aes_interval=json.dumps(interval_payload) aes_payload = crypto.encrypt(aes_interval) response = send_payload(url, encrypted_key, aes_payload) if response.status_code == 201: rdict = json.loads(response.text) response = hex2bin(rdict['message'].encode('utf-8')) plaintext = crypto.decrypt(response) return(plaintext) else: return ' '.join(['An error occurred:', str(response.status_code), response.text])
def decrypt_data(encryption_key_bundle, payload): from binascii import unhexlify from base64 import b64decode crypted_data = json.loads(payload) cipher = AESCipher(key = encryption_key_bundle, iv = crypted_data['IV'], HMAC = unhexlify(crypted_data['hmac']) ) decrypted_data = cipher.instantdecrypt(b64decode(crypted_data['ciphertext'])) return json.loads(decrypted_data.decode())
def whenPressed(self): filename = self.parent.file_sel.value key = self.parent.key_sel.values[self.parent.key_sel.value] if key is None or filename is None: npyscreen.notify_confirm("Key and/or file selected is invalid!") return cs = AESCipher(key) M = file_as_str(filename) C = cs.encrypt(M) ofname = filename + '.encrypted.asc' save_to_file(ofname, C) npyscreen.notify_confirm("Encrypted into: " + ofname)
def lambda_handler(event: dict, context: dict) -> dict: try: entropy_data = read_s3(input_path(), 'info2048.bin') except FileNotFoundError: print('Cannot read entropy file. Aborting.') sys.exit(1) try: priv_key = read_s3(input_path(), 'private.pem') private_key = RSA.importKey(priv_key) except FileNotFoundError: print('Cannot read private key file. Aborting.') sys.exit(1) rsa = OAEP() payload = event['body'] client_data = json.loads(payload) encrypted_aes_key = hex2bin(client_data['data'].encode('utf-8')) aes_key = rsa.decrypt(encrypted_aes_key, private_key) cipher = AESCipher(aes_key) encrypted_aes_payload = hex2bin(client_data['payload'].encode('utf-8')) decrypted_aes_payload = json.loads(cipher.decrypt(encrypted_aes_payload)) ranges = decrypted_aes_payload['intervals'] hashval = generate_hashval(ranges, entropy_data, MAX_SIZE) received_hashval = decrypted_aes_payload['hashval'] if received_hashval == hashval: credential_source = decrypted_aes_payload['credential_source'] plaintext = retrieve_credentials(credential_source) response = cipher.encrypt(plaintext) response = bin2hex(response).decode('utf-8') status = 201 else: response = 'not found' status = 404 return { "statusCode": status, "body": json.dumps({ 'message': response }) }
def test_cipher(self): cipher = AESCipher(None) message = ''.join( random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(100)) key = ''.join( random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(32)) # check cipher without key try: C = cipher.encrypt(message) self.assertFail() except Exception as err: self.assertEqual('Invalid key', str(err)) cipher.key = key C = cipher.encrypt(message) M = cipher.decrypt(C) self.assertEqual(M, message)
def load_keys(self, password): self.password = password if not os.path.isfile(self.filename): self.keys = [] return True # no keys saved before encrypted_keys = [] with open('.keys.json', 'r') as f: encrypted_keys = list(json.loads(f.read())) encrypted_keys, check = encrypted_keys[:-1], encrypted_keys[-1] c = AESCipher(self.password) try: if c.decrypt(check) != 'CHECK': self.password = None return False # wrong password except: return False # wrong password or corrupted file self.keys = [c.decrypt(key) for key in encrypted_keys] return True
from db.connectors import OracleConnector, PgConnector, MssqlConnector from itertools import takewhile, repeat from datetime import datetime, timezone from db.connectors import get_user_data from main.models import Hash, Database from django.conf import settings from crypto import AESCipher import typing import os aes = AESCipher(key=settings.CRYPTO_KEY) CONNECTORS: typing.Dict[str, typing.Any] = { "postgres": PgConnector, "oracle": OracleConnector, "mssql": MssqlConnector, } def get_files(walk_path, prefix="output"): out_files = [] for path, _, files in list(os.walk(walk_path)): for file in files: if file.startswith(prefix): out_files.append((path, file)) return out_files def line_count(filename): f = open(filename, "rb") f_read = f.raw.read step = 1024 * 1024 * 10
def put(self, blob): aes = AESCipher(self._get_key()) return aes.encrypt(blob)
def get(self, blob): aes = AESCipher(self._get_key()) return aes.decrypt(blob)
# Open a tun device tun = utils.tun_open(config['interface'], config['virtual_ip']) utils.iptables_setup(config['virtual_ip'], config['output']) # Now let's bind a UDP socket udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udp.bind((config['server'], config['port'])) udp.setblocking(0) logging.info('Listenning at %s:%d' % (config['server'], config['port'])) # Get descriptors tunfd = tun.fileno() udpfd = udp.fileno() # Create the cipher cipher = AESCipher(config['password']) clients = {} # Must remove timeouted clients def clearClients(): cur = time.time(); for key in clients.keys(): if cur - clients[key]['time'] >= config['timeout']: logging.info('client %s:%s timed out.' % clients[key]['ip']) del clients[key] def main_loop(): while True: r, w, x = select.select([tunfd, udpfd], [], [], 1)
def save_keys(self): c = AESCipher(self.password) encrypted_keys = [c.encrypt(key) for key in self.keys] + [c.encrypt('CHECK')] with open('.keys.json', 'w') as f: # save key f.write(json.dumps(encrypted_keys))