def __init__(self, serial_key, key_file): self.cipher = CustomCipher() key, public_key, secret_key = self.cipher.init_keys( serial_key, key_file) self.secret_key = secret_key self.public_key = public_key self.serial_key = serial_key self.key = key #print public_key #print secret_key # Ledger initialization aes_cipher = AESCipher() dev1_serial = "Device0001" dev1_serial_hash = hashlib.sha256(dev1_serial.encode()).digest() dev1_pub = aes_cipher.encrypt( RSA.importKey(open("device1-public.pem", "rb")).exportKey('PEM'), dev1_serial_hash) self.blockchain = Chain() self.blockchain.gen_next_block( hashlib.sha256("DeviceAccessBlock1".encode()).digest(), [{ "Serial": dev1_serial, "PubKey": dev1_pub }]) self.ledger = self.blockchain.output_ledger()
def start(self): # read id-pass file cipher = AESCipher(getpass()) try: id, ps = cipher.read_pass() except: print "Cannot read id-pass.txt" exit() browser = webdriver.Chrome(self.DRIVER_PATH) browser.get(self.url) try: # top page block browser.find_element_by_css_selector( "a.btn-03.str-03.str-cv").click() # login page block browser.find_element_by_name("netMemberId").send_keys(id) browser.find_element_by_name("password").send_keys(ps) browser.find_element_by_css_selector( "button.btn-03.str-03.center").click() # needs otp process # displaying charge page block print browser.find_element_by_css_selector("span.num").text # for debug(pause browser) raw_input() finally: browser.quit() """
def main(): logger.debug("AUGPAKE_SERVER_IP: {}".format(AUGPAKE_SERVER_IP)) logger.debug("AUGPAKE_SERVER_PORT: {}".format(AUGPAKE_SERVER_PORT)) logger.debug("MQTT_BROKER_IP: {}".format(MQTT_BROKER_IP)) logger.debug("MQTT_BROKER_PORT: {}".format(MQTT_BROKER_PORT)) try: ID, Key = getKeyByAugPake(AUGPAKE_SERVER_IP, AUGPAKE_SERVER_PORT) except (OSError, IndexError) as e: logger.error(e) Key = None if Key is None: logger.error("Key is None. Exit...") exit() # create cipher cipher = AESCipher(Key) for line in tailf(WATCH_FILE): logger.debug("Plain Text: {}".format(line)) encrypt_ctx = cipher.encrypt(line) prefix_encrypt = ID + SEP + encrypt_ctx logger.debug("Encrypt Text prefixed ID: {}".format(prefix_encrypt)) publish.single(MQTT_TOPIC, prefix_encrypt, hostname=MQTT_BROKER_IP, port=MQTT_BROKER_PORT)
def test_enrcypted_data_is_decrypted_properly(): aes_cipher = AESCipher(key, IV) input_data = "some data" encrypted_data = aes_cipher.encrypt(input_data) decrypted_data = aes_cipher.decrypt(encrypted_data) assert input_data == decrypted_data
def read_network_message(self, message): aes_cipher = AESCipher() if self.is_paired: message = self.decrypt(message, self.key) message = ast.literal_eval(message) if all(x in message for x in ["message", "signature", "serial"]): serial = hashlib.sha256(message['serial'].encode()).digest() data = aes_cipher.decrypt(message["message"], serial) signature = message["signature"] if self.cipher.verify(self.network_public_key, serial, data, signature): return data return None
def __init__(self): cipher = AESCipher(getpass()) try: id,ps = cipher.read_pass("gmail-id-pass.txt") except: print "Cannot read id-pass.txt" exit() try: self.gmail = imaplib.IMAP4_SSL("imap.gmail.com") self.gmail.login(id,ps) except: print "Login Failed." return
class CustomCipher: def __init__(self): self.aes_cipher = AESCipher() self.rsa_cipher = RSACipher() def init_keys(self, secret_key, key_file): key = RSA.importKey(open(key_file, "rb")) public_key = key.publickey().exportKey('PEM') secret_key = hashlib.sha256(secret_key.encode()).digest() public_key = self.aes_cipher.encrypt(public_key, secret_key) return key, public_key, secret_key def gen_keys(self, secret_key, key_file): key = self.rsa_cipher.gen_key() public_key = key.publickey().exportKey('PEM') private_key = key.exportKey('PEM') secret_key = hashlib.sha256(secret_key.encode()).digest() public_key = self.aes_cipher.encrypt(public_key, secret_key) return key, public_key, secret_key def gen_key_file(self, file_name): with open(file_name + "-private.pem", "w") as priv_file: priv_file.write("{}".format(private_key)) with open(file_name + "-public.pem", "w") as pub_file: pub_file.write("{}".format(public_key)) def encrypt(self, public_key, secret_key, message): dec_public_key = self.aes_cipher.decrypt(public_key, secret_key) key = RSA.importKey(dec_public_key) result, encrypted = self.rsa_cipher.encrypt(key, message) return encrypted def decrypt(self, enc_message, key): result, decrypted = self.rsa_cipher.decrypt(key, enc_message) return decrypted def sign(self, key, data): return self.rsa_cipher.sign(key, data) def verify(self, public_key, secret_key, data, signature): dec_public_key = self.aes_cipher.decrypt(public_key, secret_key) key = RSA.importKey(dec_public_key) return self.rsa_cipher.verify(key, data, signature)
def read_message(self, message): aes_cipher = AESCipher() message = self.cipher.decrypt(message, self.key) message = json.loads(message) if all(x in message for x in ["message", "signature", "serial"]): data = message["message"] signature = message["signature"] serial = message["serial"] secret = hashlib.sha256(serial.encode()).digest() if serial in self.ledger: dec_data = aes_cipher.decrypt(data, secret) pub_key = self.ledger[serial] if self.cipher.verify(pub_key, secret, dec_data, signature): return dec_data return None
def process_network_message(self, data): aes_cipher = AESCipher() if self.is_paired: signature = self.sign(self.key, data) enc_data = aes_cipher.encrypt( data, hashlib.sha256(self.serial_key.encode()).digest()) message = json.dumps({ "message": enc_data, "signature": signature, "serial": self.serial_key }) enc_message = self.encrypt(self.network_serial_key, self.network_public_key, message) return enc_message return None
def __init__(self, pkg_type=constants.PKG_TYPE_HELLO, pkg_num=0, data=b'', password=None): self.pkg_type = pkg_type self.pkg_num = pkg_num self.data = data self.data_length = None self.data_hash = None self.data_length = self.__calculate_data_length__() self.data_hash = self.__calculate_data_hash__() self.password = password if self.password: self.cipher = AESCipher()
def process_access_message(self, serial): aes_cipher = AESCipher() if serial in self.ledger: data = json.dumps({ "type": "response", "serial": self.serial_key, "status": "approved" }) signature = self.sign(self.key, data) enc_data = aes_cipher.encrypt( data, hashlib.sha256(self.serial_key.encode()).digest()) message = json.dumps({ "message": enc_data, "signature": signature, "serial": self.serial_key }) enc_message = self.encrypt(serial, message) return enc_message return None
def main(): global AUGPAKE_SERVER_IP global AUGPAKE_SERVER_PORT global MQTT_BROKER_IP global MQTT_BROKER_PORT if os.environ.has_key("AUGPAKE_SERVER_IP"): AUGPAKE_SERVER_IP = os.environ.get("AUGPAKE_SERVER_IP") if os.environ.has_key("AUGPAKE_SERVER_PORT"): AUGPAKE_SERVER_PORT = os.environ.get("AUGPAKE_SERVER_PORT") if os.environ.has_key("MQTT_BROKER_IP"): MQTT_BROKER_IP = os.environ.get("MQTT_BROKER_IP") if os.environ.has_key("MQTT_BROKER_PORT"): MQTT_BROKER_PORT = os.environ.get("MQTT_BROKER_PORT") print("AUGPAKE_SERVER_IP:" + AUGPAKE_SERVER_IP) print("AUGPAKE_SERVER_PORT: " + AUGPAKE_SERVER_PORT) print("MQTT_BROKER_IP:" + MQTT_BROKER_IP) print("MQTT_BROKER_PORT: " + MQTT_BROKER_PORT) Key = getKeyByAugPake(AUGPAKE_SERVER_IP, AUGPAKE_SERVER_PORT) print("encrypt key is " + Key) cipher = AESCipher(Key) while True: j = random.randint(0, 2) encrypt_ctx = cipher.encrypt(sentance[j]) print ("Sending "+ encrypt_ctx + " : " + cipher.decrypt(encrypt_ctx)) publish.single("test", encrypt_ctx, hostname=MQTT_BROKER_IP, port=int(MQTT_BROKER_PORT)) time.sleep(j+1) # sleep random time
def DecodePayload(payload): global SESSION_KEY_CACHE global SESSION_CIPHER_CACHE try: ID = payload.decode("utf-8").split(SEP)[0] msg = payload.decode("utf-8").split(SEP)[1] except IndexError as e: logger.error(e) return None if ID not in SESSION_KEY_CACHE: logger.info( "Session key for ID %s is not cached, query by thrift server." % ID) SESSION_KEY_CACHE[ID] = thrift_client.SearchKey(ID) if ID not in SESSION_CIPHER_CACHE: logger.info("Cipher for ID %s is not cached, create one." % ID) SESSION_CIPHER_CACHE[ID] = AESCipher(SESSION_KEY_CACHE[ID]) return SESSION_CIPHER_CACHE[ID].decrypt(msg)
from flask import Flask, request, jsonify from aes_cipher import AESCipher from os import urandom key = urandom(16) aes = AESCipher(key) app = Flask(__name__) @app.route('/encrypt', methods=['POST']) def encrypt(): try: data = request.get_json() for i in range(len(data['data'])): encrypt_data = aes.encrypt(data['data'][i]['text']) data['data'][i] = {"encrpyted" : encrypt_data} return jsonify(data) except: return jsonify({"message": "Something went wrong, please try again."}),400 @app.route('/decrypt', methods=['POST']) def decrypt(): try: data = request.get_json() for i in range(len(data['data'])): decrypt_data = aes.decrypt(data['data'][i]['encrpyted']) print(decrypt_data) data['data'][i] = {"text" : decrypt_data} return jsonify(data) except: return jsonify({"message": "Something went wrong, please try again."}),400
def test_given_null_key_or_iv_when_decrpyting_then_error_is_raised(): with raises(AttributeError): AESCipher(None, IV) with raises(AttributeError): AESCipher(key, None)
def __init__(self): self.aes_cipher = AESCipher() self.rsa_cipher = RSACipher()
def __init__(self): self.aes_cipher = AESCipher()
class UDPPackage(object): def __init__(self, pkg_type=constants.PKG_TYPE_HELLO, pkg_num=0, data=b'', password=None): self.pkg_type = pkg_type self.pkg_num = pkg_num self.data = data self.data_length = None self.data_hash = None self.data_length = self.__calculate_data_length__() self.data_hash = self.__calculate_data_hash__() self.password = password if self.password: self.cipher = AESCipher() def __calculate_data_length__(self): """ Calculate package data length """ return len(self.data) def __calculate_data_hash__(self): """ Calculate package data hash """ return mmh3.hash(self.data, signed=False) def __is_valid__(self): """ Checking is received data valid :return: """ logger.info("Checking is data valid") logger.debug("Data: {}".format(self.data)) calculated_hash = self.__calculate_data_hash__() logger.debug("Calculated data hash: {}".format(calculated_hash)) if calculated_hash != self.data_hash: logger.debug("Calculate hash {} does not equal to {}".format( calculated_hash, self.data_hash)) return False return True def __encrypt__(self): """ Encrypt package datae """ logger.info("Encrypt package data") key = self.cipher.gen_key(password=self.password) self.data = self.cipher.encrypt(key=key, data=self.data) def __decrypt__(self): """ Decrypt package data """ key = self.cipher.gen_key(password=self.password) self.data = self.cipher.decrypt(key=key, data=self.data) def pack(self) -> bytearray: """ Pack header and data to package :return: (byte array) Packed data to package """ if self.password: self.__encrypt__() self.data_length = self.__calculate_data_length__() self.data_hash = self.__calculate_data_hash__() logger.info("Packing data to package") logger.debug("Data length: {}".format(self.data_length)) logger.debug("Data hash: {}".format(self.data_hash)) pkg_header = struct.pack("IIII", self.pkg_type, self.pkg_num, self.data_length, self.data_hash) logger.debug("Package header: {}".format(pkg_header)) logger.debug("Package header length: {}".format(len(pkg_header))) logger.debug("Creating pkg bytearray") pkg = bytearray(pkg_header) pkg += self.data logger.debug("Data pkg: {}".format(pkg)) logger.debug("Data pkg len: {}".format(len(pkg))) return pkg def unpack(self): """ Unpack header and data from package :param data: Packed data package """ self.pkg_type, self.pkg_num, self.data_length, self.data_hash = struct.unpack( 'IIII', self.data[0:constants.TOTAL_HEADER_SIZE]) self.data = self.data[constants.TOTAL_HEADER_SIZE:] self.data_length = self.__calculate_data_length__() self.data_hash = self.__calculate_data_hash__() logger.debug("Is data valid: {}".format(self.__is_valid__())) if self.password: self.__decrypt__() def send(self, sock: struct, addr: str, port: int): """ Send data to socket :param sock: (struct) Socket :param addr: (string) Address :param port: (int) Port :return: Package object """ sock.sendto(self.pack(), (addr, port)) def receive(self, sock: struct, chunk_size: int = constants.CHUNK_SIZE) -> (struct, tuple): self.data, sender = sock.recvfrom(chunk_size + constants.TOTAL_HEADER_SIZE) logger.debug("Received: {}".format(self.data)) logger.debug("From: {}".format(sender)) self.unpack() return self, sender
class Communicator(object): def __init__(self): self.aes_cipher = AESCipher() def send_enc_message(self, message, to_pickle, client_socket): """ :param message: message to send over the socket. :param to_pickle: a boolean which means whether to pickle the message to not. :param client_socket: the socket to send the message on. """ if to_pickle: message = f'{pickle.dumps(message)}{PICKLE_BIT}' if message.find(IMAGE_SUFFIX) != -1: encrypted_message = self.aes_cipher.encrypt_image_data( message[:-len(IMAGE_SUFFIX)]) else: encrypted_message = self.aes_cipher.encrypt(message) # message sending protocol: # first you send the length of the message # and then the message itself. try: client_socket.send( str(len(encrypted_message)).zfill(LEN_OF_LENGTH)) client_socket.send(encrypted_message) except socket.error: client_socket.close() except Exception as e: pass def get_dec_message(self, client_socket): """ :param client_socket: the client to receive the message from. :return: the client's message. """ message_length = self.get_message_length(client_socket) encrypted_message = self.get_message_by_length(message_length, client_socket) if encrypted_message.find(IMAGE_SUFFIX) is not -1: return self.aes_cipher.encrypt_image_data( encrypted_message[:-len(IMAGE_SUFFIX)]) decrypted_message = self.aes_cipher.decrypt(encrypted_message) if decrypted_message[-1:] == PICKLE_BIT: return pickle.loads(decrypted_message) return decrypted_message @staticmethod def get_message_length(client_socket): """ the function receives the length of the message. :return: the message length """ message_length = "" while len(message_length) != LEN_OF_LENGTH: message_length += client_socket.recv(LEN_OF_LENGTH - len(message_length)) return int(message_length) @staticmethod def get_message_by_length(message_length, client_socket): """ :param message_length: the length of the message. :param client_socket: the socket to listen on. :return: the message that was received. """ content = "" while len(content) != message_length: content += client_socket.recv(message_length - len(content)) return content
# Client that makes request to a production server import base64 import random import string import requests import json import logging import configs.pentagon as config from aes_cipher import AESCipher cipher = AESCipher(config.AES_PASSPHRASE) def make_request(image, id, daytime, is_last=False): img_path = '/root/Projects/Final_Final/Godfather/cars/' + '{}'.format(daytime) + '_{}'.format(id) + '.jpg' with open(img_path, 'wb') as imgfile: imgfile.write(image) image_string = base64.b64encode(image).decode('utf-8') json_request = {'cookie': config.HTTP_COOKIE, 'image': image_string, 'img_path': img_path} if is_last: json_request['last_image'] = True json_string = json.dumps(json_request) encr_request = cipher.encrypt(json_string) try:
def get_aes_cipher(): return AESCipher(AES_KEY.decode("hex"), AES_IV.decode("hex"))
'cancel_transfer_from_savings_operation': op_cancel_transfer_from_savings, 'decline_voting_rights_operation': op_decline_voting_rights, 'create_proposal_operation': op_create_proposal, 'remove_proposal_operation': op_remove_proposal, 'update_proposal_votes_operation': op_update_proposal_votes, 'claim_reward_balance2_operation': op_claim_reward, 'vote2_operation': op_vote, 'proposal_pay_operation': op_proposal_pay, 'interest_operation': op_interest, 'fill_vesting_withdraw_operation': op_fill_vesting_withdraw, 'fill_order_operation': op_fill_order, 'shutdown_witness_operation': op_shutdown_witness, 'producer_reward_operation': op_producer_reward, 'request_account_recovery_operation': op_request_account_recovery, 'custom_operation': op_custom, 'limit_order_create2_operation': op_limit_order_create, 'limit_order_cancel2_operation': op_limit_order_cancel, 'account_update2_operation': op_account_update2 } cipher = AESCipher(input()) def anonymize(op): if op['type'] not in dispatcher.keys(): with open('not_anonymized.txt', 'ab') as f: f.write(json.dumps(op).encode('utf-8')) f.write('\n'.encode('utf-8')) op['value'] = dispatcher[op['type']](op['value']) return op
import random import string from aes_cipher import AESCipher key_text = ''.join( [random.choice(string.ascii_letters + string.digits) for i in range(32)]) plain_text = 'test message.' cipher = AESCipher(key_text) encrypted = cipher.encrypt(plain_text) print(encrypted) decrypted = cipher.decrypt(encrypted) print(decrypted) print(decrypted == plain_text)