Esempio n. 1
0
def get_data(image_data, bits_to_rewrite_count, key):
    cipher = AESCipher(key)

    image_bytes_count = int(math.ceil(64 * 8 / bits_to_rewrite_count))

    i_str = StringIO()
    for i in range(image_bytes_count):
        i_str.write(H.get_bits(image_data[i])[-bits_to_rewrite_count:])
    bin_enc_size = i_str.getvalue()[:64 * 8]

    i_bytes = BytesIO()
    for i in range(64):
        i_bytes.write(bytes([int(bin_enc_size[8 * i:8 * i + 8], 2)]))
    enc_size = i_bytes.getvalue()

    size = int(cipher.decrypt(enc_size))

    shift = image_bytes_count

    image_bytes_count = int(math.ceil(size * 8 / bits_to_rewrite_count))

    for i in range(image_bytes_count):
        i_str.write(H.get_bits(image_data[i + shift])[-bits_to_rewrite_count:])
    bin_enc_data = i_str.getvalue()[64 * 8:(size + 64) * 8]

    i_bytes = BytesIO()
    for i in range(size):
        i_bytes.write(bytes([int(bin_enc_data[8 * i:8 * i + 8], 2)]))
    enc_data = i_bytes.getvalue()

    data = cipher.decrypt(enc_data).encode()
    return data
Esempio n. 2
0
class QRCipher:
    def __init__(self, key, file_name):
        self.key = key
        self.file_name = file_name
        self.cipher = AESCipher(bytes(self.key, encoding='utf8'))

    def set_key(self, key):
        self.key = key
        self.cipher = AESCipher(bytes(self.key, encoding='utf8'))

    @staticmethod
    def create_qr(text, qr_name):
        qr_code = pyqrcode.create(text)
        qr_code.png(qr_name, scale=6)
        # text_qr.svg('uca-url.svg', scale=8)
        # text_qr.eps('uca-url.eps', scale=2)
        # print(text_qr.terminal(quiet_zone=1))
        return qr_code

    @staticmethod
    def decode_qr_image(image_name):
        data = decode(Image.open(image_name))
        text = data[0].data
        return text

    def encrypt(self, plain_text):
        encrypted_text = self.cipher.encrypt(plain_text)
        return self.create_qr(encrypted_text,
                              'encrypted_' + self.file_name + '.png')

    def decrypt(self, encrypted_text):
        decrypted_text = self.cipher.decrypt(encrypted_text)
        return self.create_qr(decrypted_text,
                              'decrypted_' + self.file_name + '.png')
Esempio n. 3
0
 def decrypt_file(self, file_name):
     aes = AESCipher(self.key)
     with open(file_name, 'rb') as file:
         text = file.read()
     dec = aes.decrypt(text)
     with open(file_name, 'wb') as file:
         file.write(dec)
Esempio n. 4
0
def run_client(port):
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((HOST, port))

    cred = s.recv(RECV_SIZE)
    while True:
        try:
            pub, sig = unpack_cred(cred)
            break
        except:
            cred += s.recv(RECV_SIZE)

    if not verify_cred(pub, sig):
        return

    key = RSA.importKey(pub)
    rsa = PKCS1_OAEP.new(key)

    sess_key = secrets.token_bytes(KEY_SIZE)
    enc_sess_key = rsa.encrypt(sess_key)

    s.sendall(pickle.dumps(enc_sess_key))

    cipher = AESCipher(sess_key)
    messages = []
    data = recvall(s)
    while data:
        chunk = pickle.loads(data)
        data = data[len(pickle.dumps(chunk)):]
        messages.append(cipher.decrypt(chunk))

    with open('msgs.txt', 'wb') as f:
        f.write(b''.join(messages))
Esempio n. 5
0
    def DH(self, sharedKey):
        print '\n############### STARTING D-H ##################'
        # Create AES object with shared key
        cipher = AESCipher(sharedKey)

        #generate key to send to server
        myDiffieHellman = DiffieHellman()
        print 'g^a mod p value is: ', myDiffieHellman.public_key

        print '\n'

        #send key to server
        sendDH = cipher.encrypt(str(myDiffieHellman.public_key))
        print 'Sending encrypted value: ', sendDH.encode('hex')
        self.send(str(sendDH))

        print '\n'

        recvDH = self.waitToRec()

        #decrypt received DH value
        reply = cipher.decrypt(recvDH)
        print 'Received encrypted value: ', recvDH.encode('hex')
        print '\n'
        print 'g^b mod p value is: ', reply
        print '\n'

        #calculate session key
        myDiffieHellman.calc_shared_key(long(reply))
        print "Calculated session key:", myDiffieHellman.key
        self.sessionKey = myDiffieHellman.key

        print '################## D-H OVER ###################\n'
	def generate_splits(self):
		aes = AESCipher(self.key)
		cipher = aes.encrypt(self.text)
		message = aes.decrypt(cipher)
		size = 255, len(self.key)
		im = Image.new("1", size, "white")
		pix =  im.load()
		for i in range(len(self.key)):
			for j in range(ord(self.key[i])):
				pix[j, i] = 0
		im.save("original.gif")
		share1 = Image.new("1", size, "white")
		share1pix = share1.load()
		for i in range(len(self.key)):
			for j in range(255):
				x = randint(0,1)
				if x == 0:
					share1pix[j, i] = 0
		share2 = Image.new("1", size)
		share2pix = share2.load()
		for i in range(len(self.key)):
			for j in range(255):
				if pix[j, i] == share1pix[j, i]:
					share2pix[j, i] = 0
				else:
					share2pix[j, i] = 255
		output = [share1, share2, cipher]
		x = Decrypter(cipher, [share1, share2])
		x.decrypt_image()
		return output
Esempio n. 7
0
def decrypt_token(ticket, privatekey):
    """
        token contains: (generated session key, expiry date) encrypted with 
        ticket contains: 
    """
    privkey_path = "./client.key"
    pubkey_path = "./client_pub.key"

    # encrypting the whole ticket with client's password or public key

    cipher = PKCS1_OAEP.new(privatekey)

    ticket = cipher.decrypt(ticket)

    ticket = json.loads(ticket)
    print(ticket)

    from AESCipher import AESCipher
    cipher = AESCipher(SHARED_SECRET)

    token = cipher.decrypt(ticket['token'])
    token = json.loads(token)

    print(token, ticket)
    return
Esempio n. 8
0
 def decrypt_payload(self, encrypt_payload, user_id):
     aeskey = self.get_token(user_id)
     aesiv = self.get_iv(user_id)
     aesc = AESCipher(aeskey)
     aesc.set_iv(aesiv)
     decrypted_bytes = aesc.decrypt(encrypt_payload)
     # decrypted_bytes.hex()
     return decrypted_bytes
Esempio n. 9
0
 def decrypt_payload(self, pkt, aes_key, aes_iv):
     #aes_key = b'\x9b\xd9\xcd\xf6\xbe+\x9dX\xfb\xd2\xef>\xd87i\xa0\xca\xf5o\xd0\xac\xc3\xe0R\xf0z\xfa\xb8\xdd\x01?E'
     #aes_iv = b'\xef\xaa)\x9fHQ\x0f\x04\x18\x1e\xb5;B\xff\x1c\x01'
     aesc = AESCipher(aes_key)
     aesc.set_iv(aes_iv)
     decrypted_bytes = aesc.decrypt(pkt)
     # decrypted_bytes.hex()
     return decrypted_bytes
	def decrypt_image(self):
		key = self.get_key_from_image()
		cipher = self.cipher
		aes = AESCipher(key)
		base64_decoded = aes.decrypt(cipher)
		fh = open("decryptedImage.png", "wb")
		fh.write(base64_decoded.decode('base64'))
		fh.close() 
def save_record(account):
    print(request.content_type)
    if not request.json or not 'size' in request.json:
        raise InvalidUsage('Invalid usage of this web-service detected',
                           status_code=400)

    size = int(request.json['size'])
    decoded_compressed_record = request.json.get('data', "")
    symmetricKeyEncrypted = request.json.get('key', "")

    compressed_record = base64.b64decode(decoded_compressed_record)
    encrypted_json_record_str = zlib.decompress(compressed_record)

    pks1OAEPForDecryption = PKS1_OAEPCipher()
    pks1OAEPForDecryption.readDecryptionKey('decryption.key')
    symmetricKeyDecrypted = pks1OAEPForDecryption.decrypt(
        base64.b64decode(symmetricKeyEncrypted))

    aesCipherForDecryption = AESCipher()
    aesCipherForDecryption.setKey(symmetricKeyDecrypted)

    json_record_str = aesCipherForDecryption.decrypt(encrypted_json_record_str)

    record_as_dict = json.loads(json_record_str)

    # Add the account ID to the reading here
    record_as_dict["account"] = account

    #print record_as_dict
    post_id = mongo_collection.insert_one(record_as_dict).inserted_id
    print('Saved as Id: %s' % post_id)

    producer = KafkaProducer(
        bootstrap_servers=['your.kafka.server.com:9092'],
        value_serializer=lambda m: json.dumps(m).encode('ascii'),
        retries=5)
    # send the individual records to the Kafka queue for stream processing
    raw_readings = record_as_dict["data"]
    counter = 0
    for raw_reading in raw_readings:
        raw_reading["id"] = str(post_id) + str(counter)
        raw_reading["account"] = account
        producer.send("car_readings", raw_reading)
        counter += 1

    producer.flush()
    # send the summary to the Kafka queue in case there is some stream processing required for that as well
    raw_summary = record_as_dict["summary"]
    raw_summary["id"] = str(post_id)
    raw_summary["account"] = account
    raw_summary["eventTime"] = record_as_dict["timestamp"]
    producer.send("car_summaries", raw_summary)

    producer.flush()
    return jsonify({'title': str(size) + ' bytes received'}), 201
Esempio n. 12
0
 def decrypt_image(self, k):
     #key = self.get_key_from_image()
     key = k
     cipher = self.cipher
     aes = AESCipher(key)
     base64_decoded = aes.decrypt(cipher)
     #print(type(base64_decoded))
     fh = open("decryptedImage.png", "wb")
     fh.write(base64.b64decode(base64_decoded))
     #fh.write(base64_decoded.decode('base64'))
     fh.close()
     return (base64.b64decode(base64_decoded))
Esempio n. 13
0
 def load_session(self):
     loaded_session = None
     cipher = AESCipher()
     with open('session', 'rb') as f:
         enc = f.read()
     try:
         plain = cipher.decrypt(enc)
         loaded_session = json.loads(str(plain))
         self.username = loaded_session['username']
         self.password = loaded_session['passwd']
     finally:
         return loaded_session
Esempio n. 14
0
File: api.py Progetto: bebound/Pixiv
 def load_session(self):
     loaded_session = None
     cipher = AESCipher()
     with open('session', 'rb') as f:
         enc = f.read()
     try:
         plain = cipher.decrypt(enc)
         loaded_session = json.loads(str(plain))
         self.username = loaded_session['username']
         self.password = loaded_session['passwd']
     finally:
         return loaded_session
Esempio n. 15
0
def load(key):
    """ Get the passwords stored in the database and decrypt them """
    cipher = AESCipher(key)
    db = Database()
    entries = db.load_entries()
    tmp = []
    for entry in entries:
        try:
            entry_2 = cipher.decrypt(entry[2])
        except Error as e:
            print("Error: " + str(e))
        tmp.append([entry[0], entry[1], entry_2])
    return tmp
Esempio n. 16
0
    def mutAuthClient(self, sharedKey):
        try:
            # Create AES object with shared key
            cipher = AESCipher(sharedKey)

            # Client's challenge to server
            Ra = Random.new().read(16)
            print 'Ra:', Ra.encode('hex')
            message= 'Client'+ Ra
            print 'Sending message:', message
            self.send(message)

            # Wait for response from server
            reply = self.waitToRec()
            print 'Received:', reply.encode('hex')

            # Decrypt response
            plainText = cipher.decrypt(reply)
            print 'Decrypted:', plainText

            # Obtain Ra and Rb from response
            RaTest = plainText[-32:-16]
            print 'Ra received:', RaTest.encode('hex')
            Rb=plainText[-16:]
            print 'Rb received:', Rb.encode('hex')

            # Compare received Ra with sent Ra
            if RaTest!= Ra:
                print 'Different Ra received: mutual auth failed'
                self.close()
                sys.exit(1)

            # Encrypt "name","Rb" with shared key and send it
            finalReply = 'Client' + Rb
            print 'Encrypting reply:', finalReply
            finalCipher = cipher.encrypt(finalReply)
            print 'Sending cipher:', finalCipher.encode('hex')
            self.send(finalCipher)

            # Wait for response from server
            replyauth = self.waitToRec()
            if replyauth == 'mutual auth failed':
                print 'Server denied authentication: mutual auth failed'
                self.close()
                sys.exit(1)
            else:
                print 'CLIENT: mutual auth passed'
        except:
            print 'Mutual auth failed'
            self.close()
            sys.exit(1)
def get_hot_wallet():
    global HOT_WALLET_PASSWORD
    wallet_dir, wallet_id = get_wallet_dir(), get_default_wallet()

    if HOT_WALLET_PASSWORD is None:
        # Try empty password first (Reminder: in production there should always be a decryption password for the hot wallet)
        try:
            cipher = AESCipher(key='')
            with open(os.path.join(wallet_dir, '%s.enc' % wallet_id), 'r') as input_file:
                encrypted_data = input_file.read()
                return simplejson.loads(cipher.decrypt(encrypted_data))

        except Exception as ex:
            prompt_decryption_password()

    try:
        cipher = AESCipher(key=HOT_WALLET_PASSWORD)
        with open(os.path.join(wallet_dir, '%s.enc' % wallet_id), 'r') as input_file:
            encrypted_data = input_file.read()
            return simplejson.loads(cipher.decrypt(encrypted_data))

    except Exception:
        raise Exception('Invalid password to decrypt hot wallet!')
Esempio n. 18
0
 def load_session(self):
     cipher = AESCipher()
     with open('session', 'rb') as f:
         enc = f.read()
     try:
         plain = cipher.decrypt(enc)
         loaded_session = json.loads(str(plain))
         self.access_token = loaded_session['access_token']
         self.refresh_token = loaded_session['refresh_token']
         return True
     except:
         print(
             "error when load session, please delete session file and try again."
         )
Esempio n. 19
0
File: amy.py Progetto: xbili/cs2105
def receive_messages(skt, sess_key):
    msg = open('msgs.txt', 'w')
    data = skt.recv(1024)
    while data:
        data_arr = split_combined_pickle(data)
        for item in data_arr:
            if not item is None:
                item = pickle.loads(item)
                cipher = AESCipher(sess_key)
                decrypted = cipher.decrypt(item)
                msg.write(decrypted)
        data = skt.recv(1024) # Fetch next packet
    msg.close()
    skt.close()
def decrypt_msg(content, token):

    client_key = decrypt_token(token)
    if client_key is None:
        return None
    else:

        cipher = AESCipher(client_key["gen_session_key"])
        try:
            msg = json.loads(cipher.decrypt(content))
            # malicious user
        except json.decoder.JSONDecodeError as e:
            return none
        return msg, client_key["gen_session_key"]
Esempio n. 21
0
    def waitForMessage(self):
        sessionCipher = AESCipher(str(self.sessionKey))
        while True:
            try:
                reply = self.sock.recv(1024).strip()

                #decrypt message gotten from server
                plainText = sessionCipher.decrypt(reply)
                print '\n$$$$$$$$$$$$$$ RECIEVING MESSAGE $$$$$$$$$$$$$$'
                print 'Encrypted message received: ', reply.encode('hex')
                print 'Decrypted message:', plainText
                print '$$$$$$$$$$$$$$ END OF MESSAGE $$$$$$$$$$$$$$$$$\n'
            except:
                print 'Connection closed'
                return
Esempio n. 22
0
class P2PConnection(Connection):
    def __init__(self, ip_address, port, key):
        Connection.__init__(self, ip_address, port)
        self.key = key
        self.aes = AESCipher(key)

    def sendChat(self, msg):
        self.send(self.aes.encrypt(msg))

    def recvChat(self):
        return self.aes.decrypt(self.recv())

    def tryRecvChat(self):
        sok = select.select([self.socket], [], [], 0)
        if not sok[0]:
            return self.recvChat()
Esempio n. 23
0
    def serverRecv(self):
        sessionCipher = AESCipher(str(self.sessionKey))
        while True:
            try:
                #get message from client
                cipherText = self.clientSock.recv(1024).strip()
                
                #decrypt the cipherText
                plainText = sessionCipher.decrypt(cipherText)
                print '\n$$$$$$$$$$$$$$ RECIEVING MESSAGE $$$$$$$$$$$$$$'
                print 'Encrypted message received:', cipherText.encode('hex')
                print 'Decrypted message:', plainText
                print '$$$$$$$$$$$$$$ END OF MESSAGE $$$$$$$$$$$$$$$$$\n'

            except:
                return
Esempio n. 24
0
    def send_request(self, payload, url):
        """Sends a REST post request to NoPassword API
        :param payload: Data
        :param url: REST url
        :return: json
        """
        now = str(datetime.utcnow())
        now = now[:19] + "Z"
        payload = json.dumps(payload).encode()
        payload = base64.b64encode(payload).decode()
        signature = self.rsaCipher.sign(now + payload)

        request = {
            "Payload": payload,
            "Timestamp": now,
            "Signature": signature,
            "Key": self.GENERIC_API_KEY
        }
        headers = {"Content-type": self.APPLICATION_JSON}
        response = requests.post(url, json.dumps(request), headers=headers)

        if response.status_code == HTTPStatus.OK.value:
            try:
                jresp = response.json()
            except Exception as err:
                print("json expected:", err)
                print("response =", response.content)
                return None

            if jresp["Succeeded"]:
                enc_key = self.rsaCipher.decrypt(jresp["Value"]["EncKey"])
                enc_key = json.loads(enc_key)
                aes_key = base64.b64decode(enc_key["K"])
                aes_iv = base64.b64decode(enc_key["V"])
                aes_cipher = AESCipher(aes_key, aes_iv, self.UTF_ENCODING)
                payload = aes_cipher.decrypt(jresp["Value"]["Payload"])
                return json.loads(payload)
            else:
                print("error:", jresp["Message"])
                # print("request =", json.dumps(request, indent=4))
                # print("response =", response.content)
                return None

        else:
            print("error:", response.text)

        return None
def decrypt_token(token):

    from AESCipher import AESCipher
    # decrypt
    cipher = AESCipher(SHARED_SCERET)

    client_msg = cipher.decrypt(token)
    client_key = json.loads(token)
    """
        client_key: gen_session_key, expiry date
    """
    # decrypting the msg using gen_session_key
    expiry_date = datetime.datetime.fromtimestamp(
        int(client_key["expiry_date"]))
    if datetime.datetime.now() > expiry_date:
        return None
    else:
        return client_key
Esempio n. 26
0
File: Alice.py Progetto: plty/nus
def run_client(port):
    key = read_key("bob-python.pub")
    rsa = PKCS1_OAEP.new(key)

    sess_key = secrets.token_bytes(KEY_SIZE)
    enc_sess_key = rsa.encrypt(sess_key)

    s = socket(AF_INET, SOCK_STREAM)
    s.connect((HOST, port))
    s.sendall(pickle.dumps(enc_sess_key))

    cipher = AESCipher(sess_key)
    messages = []
    data = recvall(s)
    while data:
        chunk = pickle.loads(data)
        data = data[len(pickle.dumps(chunk)):]
        messages.append(cipher.decrypt(chunk))

    with open('msgs.txt', 'wb') as f:
        f.write(b''.join(messages))
Esempio n. 27
0
def load_wallet():
    global WALLET_ID
    if args.wallet is not None:
        WALLET_ID = args.wallet

    if not os.path.isfile(os.path.join(WALLET_DIR, '%s.enc' % WALLET_ID)):
        return {}

    cipher = AESCipher(
        key=getpass.getpass('Enter the password to decrypt the hot wallet: '))
    try:
        with open(os.path.join(WALLET_DIR, '%s.enc' % WALLET_ID),
                  'r') as input_file:
            encrypted_data = input_file.read()
            return simplejson.loads(cipher.decrypt(encrypted_data))

    except IOError as ex:
        print('Unable to load encrypted wallet: %s' % ex, file=sys.stderr)
        sys.exit(1)
    except Exception as ex:
        print('Unable to decrypt wallet: %s' % ex, file=sys.stderr)
        sys.exit(1)
Esempio n. 28
0
class P2PConnection(Connection):
    def __init__(self, ip_address, port, key):
        Connection.__init__(self, ip_address, port)
        self.key = key
        self.aes = AESCipher(key)

    def sendChat(self, msg):
        self.send(self.aes.encrypt(msg))

    def recvChat(self):
        try:
            return self.aes.decrypt(self.recv())
        except Exception as er:
            raise SChatError('Problem with decryption of the recived data - ' +
                             str(er))

    def tryRecvChat(self):
        if self.isNewMsg():
            return self.recvChat()

    def startChat(self):
        self.settimeout(None)
Esempio n. 29
0
def receive_messages(skt, sess_key):
    # because each line is sent by pickling
    # it might be better to read from the socket
    # as a stream and let pickle do its job
    msg = open('msgs.txt', 'w')
    data = skt.recv(1024)
    count = 1
    while data:
        data_arr = split_combined_pickle(data)
        for item in data_arr:
            print item
            if not item is None:
                item = pickle.loads(item)
                cipher = AESCipher(sess_key)
                decrypted = cipher.decrypt(item)
                msg.write(decrypted)
        data = skt.recv(1024) # Fetch next packet
        count += 1

    print 'received', count
    # Proper teardown
    msg.close()
    skt.close()
Esempio n. 30
0
def receive_messages(skt, sess_key):
    # because each line is sent by pickling
    # it might be better to read from the socket
    # as a stream and let pickle do its job
    msg = open('msgs.txt', 'w')
    data = skt.recv(1024)
    count = 1
    while data:
        data_arr = split_combined_pickle(data)
        for item in data_arr:
            print item
            if not item is None:
                item = pickle.loads(item)
                cipher = AESCipher(sess_key)
                decrypted = cipher.decrypt(item)
                msg.write(decrypted)
        data = skt.recv(1024)  # Fetch next packet
        count += 1

    print 'received', count
    # Proper teardown
    msg.close()
    skt.close()
Esempio n. 31
0
 def decrypt_password(self, host):
     cipher = AESCipher(base64.decodestring(host['key']))
     return cipher.decrypt(host['password'])
Esempio n. 32
0
File: test.py Progetto: mhdr/Thesis
from AESCipher import AESCipher

a=AESCipher("0123456789ABCDEF")
b=AESCipher("0123456789ABCDEF")

message= a.encrypt("Hello World")
print(message)

decryped=b.decrypt(message)
print(decryped)
Esempio n. 33
0
class DataServerMainServerProtocol:
    def __init__(self, my_socket, saving_path):
        """
        constructor
        :param my_socket: the socket that connects with server
        :param saving_path: the path to save file parts
        """
        self.saving_path = saving_path
        random_generator = Random.new().read
        self.RSA_key = RSA.generate(
            1024, random_generator)  # generate pub and priv key
        self.AES_cipher = None
        self.my_socket = my_socket
        self.msg_type_disassemble = {
            0: self.disassemble_0_key_exchange,
            3: self.disassemble_3_upload_file,
            4: self.disassemble_4_get_file,
            5: self.disassemble_5_delete_file
        }  # msg type (int) : method that disassemble the msg parameters
        self.msg_type_build = {
            0: self.build_0_key_exchange,
            4: self.build_4_get_file
        }  # msg type (int) : method that build the msg to send, the msg parameters part

    def export_RSA_public_key(self):
        """
        :return: return the public rsa as key
        """
        return self.RSA_key.publickey().exportKey()

    def create_AES_key(self, password):
        """
        :param password: the AES key
        create AES class base on that key
        """
        self.AES_cipher = AESCipher(password)

    def recv_msg(self, first=False):
        """
        :param first: check if it is the first msg -> if it is encrypted, and how
        :return: (msg type, msg parameters - [], if the connection fails - boolean)
        """
        connection_fail = False
        # recv the msg length
        try:
            msg_len = self.my_socket.recv(1)
        except:
            return -1, [], True
        while msg_len[-1] != "$":
            try:
                msg_len += self.my_socket.recv(1)
            except:
                return -1, [], True
        msg_len = int(msg_len[:-1])
        try:
            msg = self.my_socket.recv(msg_len)
        except:
            return -1, [], True

        msg_type, msg_parameters = self.disassemble(msg, first)

        return msg_type, msg_parameters, connection_fail

    def send_msg(self, msg):
        """
        :param msg: the raw msg to send
        :return: if the sending is a success
        """
        connection_fail = False
        try:
            self.my_socket.send(msg)
        except:
            connection_fail = True
        return connection_fail

    def get_msg_type(self, msg):
        """
        :param msg: the raw full msg - string (without the len of the msg) (len > 0)
        :return: msg type - int, msg msg without the msg_type part
        """
        end_of_msg_type = msg.find("$")
        msg_type = int(msg[:end_of_msg_type])
        msg = msg[end_of_msg_type + 1:]
        return msg_type, msg

    def disassemble(self, msg, first):
        """
        :param first: if it is the first msg from MainServer
        :param msg: the raw full msg - string (without the len of the msg) (len > 0)
        :return: msg type - int, msg parameters - array []
        """
        if first:
            msg = self.RSA_key.decrypt(msg)
        else:
            msg = self.AES_cipher.decrypt(msg)
        msg_type, msg = self.get_msg_type(msg)
        msg_parameters = self.msg_type_disassemble[msg_type](msg)
        return msg_type, msg_parameters

    def disassemble_0_key_exchange(self, msg):
        """
        :param msg: the msg parameters
        :return: msg parameters - in array []
        """
        return [msg]

    def disassemble_3_upload_file(self, msg):
        """
        :param msg: the msg parameters
        :return: msg parameters - in array [file part path]
        """
        name_len = int(msg[:msg.find("$")])
        name = msg[msg.find("$") + 1:msg.find("$") + 1 + name_len]
        msg = msg[msg.find("$") + 1 + name_len:]
        data_len = int(msg[:msg.find("$")])
        data = msg[msg.find("$") + 1:msg.find("$") + 1 + data_len]
        file_part_path = self.saving_path + "\\" + name
        with open(file_part_path, "wb") as f:
            f.write(data)
        return [file_part_path]

    def disassemble_4_get_file(self, msg):
        """
        :param msg: the msg parameters
        :return: msg parameters - in array [file_name, port]
        """
        name_len = int(msg[:msg.find("$")])
        name = msg[msg.find("$") + 1:msg.find("$") + 1 + name_len]
        port = int(msg[msg.find("$") + 1 + name_len:])
        return [name, port]

    def disassemble_5_delete_file(self, msg):
        """
        :param msg: the msg parameters - just the name
        :return: msg parameters - in array [file_name]
        """
        return [msg]

    def build(self, msg_type, msg_parameter):
        """
        :param msg_type: int - the msg type as above
        :param msg_parameter: array of the parameters
        :return: a string that will be send by the socket to the main server
        """
        msg = str(msg_type) + "$" + self.msg_type_build[msg_type](
            msg_parameter)
        if msg_type != 0:
            encrypted_msg = self.AES_cipher.encrypt(msg)
        else:
            encrypted_msg = msg
        encrypted_msg = str(len(encrypted_msg)) + "$" + encrypted_msg
        return encrypted_msg

    def build_0_key_exchange(self, msg_parameters):
        """
        :param msg_parameters: [key]
        :return: key
        """
        return msg_parameters[0]

    def build_4_get_file(self, msg_parameters):
        """
        :param msg_parameters: [file_name,file_path]
        :return: file name and file data
        """

        file_name = msg_parameters[0]
        if msg_parameters[1] != "":
            with open(msg_parameters[1], "rb") as f:
                file_data = f.read()
        else:
            file_data = ""
        msg = str(len(file_name)) + "$" + file_name + str(
            len(file_data)) + "$" + file_data
        return msg
Esempio n. 34
0
class PassStorage(object):
    def __init__(self, path, password):
        self._path = path
        self._password = password
        self._cipher = AESCipher(self._password)
        self._data = {}

        try:
            self.load()

        except (UnicodeDecodeError, ValueError):
            raise Exception("Invalid password")


    def load(self):
        if os.path.exists(self._path):
            with open(self._path, "rb") as f:
                encrypted = f.read()
                js_data = self._cipher.decrypt(encrypted)
                self._data = json.loads(js_data)
        else:
            self.save()


    def save(self):
        with open(self._path, "wb") as f:
            js_data = json.dumps(self._data)
            encrypted = self._cipher.encrypt(js_data)
            f.write(encrypted)


    def changepass(self, oldpass, newpass):
        if oldpass == self._password:
            self._password = newpass
            self._cipher = AESCipher(self._password)
            self.save()
            return True

        else:
            return False


    def rows(self):
        return self._data.keys()


    def add(self, title):
        if title not in self._data:
            self._data[title] = {}
            self.save()
            return True
        else:
            return False


    def remove(self, title):
        if title in self._data:
            del self._data[title]
            self.save()
            return True
        else:
            return False


    def modify(self, title, key, value):
        if title in self._data:
            self._data[title][key] = value
            self.save()
            return True
        else:
            return False


    def delkey(self, title, key):
        if title in self._data and key in self._data[title]:
            del self._data[title][key]
            return True
        else:
            return False


    def keys(self, title):
        return self._data[title].keys()


    def value(self, title, key):
        return self._data[title][key]
Esempio n. 35
0
class Alice():

  def __init__(self, host, port):
    self.session_key = self.generate_random_key()
    self.host = host
    self.port = port
    self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.socket.connect((host, port))
    self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.aes = AESCipher(self.session_key)

  @staticmethod
  def generate_random_key():
    return os.urandom(BS)

  def encrypt_session_key(self, public_key):
    self.encrypted_session_key = public_key.encrypt(self.session_key)

  def send_message(self, message):
    lol = pickle.dumps(message)
    self.socket.send(lol)
    pass

  def receive_message(self):
    return self.socket.recv(BUFFER_SIZE)

  def get_public_key(self):
    with open(PUBLIC_KEY_FILE, "r") as f:
      public_key = RSA.importKey(f.read())
    return PKCS1_OAEP.new(public_key)

  def receive_all_message(self):
    messages = ''

    while(True):
      message = self.receive_message()
      if (len(message) == 0):
        break
      messages += message

    return messages

  def decode_message(self, messages):
    message_list = messages.split(".")

    full_message = ''

    for message in message_list:
      if (len(message) == 0):
        break
      real_message = pickle.loads(message+'.')
      full_message += self.aes.decrypt(real_message)

    return full_message

  def write_to_file(self, message):

    with open(OUTPUT_FILE, 'w') as f:
      f.seek(0)
      f.truncate()
      f.write(message)

  def connect(self):
    # get public key from file
    public_key = self.get_public_key()

    # encrypt session key
    self.encrypt_session_key(public_key)

    # send encrypted session key
    self.send_message(self.encrypted_session_key)

    # receive all message
    messages = self.receive_all_message()

    # get plaintext message
    messages = self.decode_message(messages)

    # write to file
    self.write_to_file(messages)

    # close socket
    self.socket.close()
Esempio n. 36
0
if (len(sys.argv) < 2):
    print "need a filename"
    exit(1)

inputname = sys.argv[1]


passPhraseName= "MyPhraseName"
passPhrase = "rosebud"
#inputname = "declaration.txt.{0}".format(passPhraseName)
outputname = "{0}-decrypted.txt".format(inputname)

#obtain ciphertext 
fh = open(inputname)
ciphertext = fh.read()
fh.close()

#encrypt the cleartext and write to a file
#use the MD5 of the passphrase as the key
enckey = hashlib.sha256(passPhrase).digest()
aes = AESCipher(enckey)
cleartext = aes.decrypt(ciphertext)

#truncate file if it exists
outfile = open(outputname,'w+')
outfile.write(cleartext) 
outfile.close()
print "Completed"

Esempio n. 37
0
    encrpyt_mapping.append(col)
    encrpyt_mapping.append(str(col) + " decrypted_value")

for csv_file in csv_files:
    print "Parsing csv file  %s" % csv_file
    mapping_df = DataFrame(columns=encrpyt_mapping)
    data = read_csv(os.path.join(csv_dir, csv_file), error_bad_lines=False, names=header_row, dtype='unicode')
    print "Encrypting of data in csv file %s is starting" % csv_file

    for col in columns_to_decrypt:
        print(col)
        for index, row in data.iterrows():
            # i = 0
            #print str(row[col])
            """if isinstance(row[col], float):
                if math.isnan(row[col]):
                    row[col] = str(row[col])
                else:
                    row[col] = int(row[col])"""
            data.loc[index, col] = cypher_obj.decrypt(str(row[col]))
            #encoded = cypher_obj.encrypt(str(row[col]))
            #data.loc[index, col] = encoded
            # print(encoded + " " + cypher_obj.decrypt(encoded))
            # mapping_df.loc[index, encrpyt_mapping[i]] = row[col]
            # mapping_df.loc[index, encrpyt_mapping[i+1]] = encoded
            # i += 2
    print "Decrypting of data in csv file %s is completed" % csv_file
    print "Writing CSV file for decrypted data"
    data.to_csv(os.path.join(csv_dir, "dec_" + csv_file), encoding='utf-8')
    # mapping_df.to_csv(os.path.join(csv_dir, "mapping_" + csv_file), encoding='utf-8')
Esempio n. 38
0
 def decrypt_password(self, host):
     cipher = AESCipher(base64.decodestring(host['key']))
     return cipher.decrypt(host['password'])
Esempio n. 39
0
class Amy:
    def __init__(self, host, port):
        self.session_key = self.generate_random_key()
        self.host = host
        self.port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((host, port))
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.aes = AESCipher(self.session_key)

    @staticmethod
    def generate_random_key():
        return os.urandom(BS)

    def encrypt_session_key(self, public_key):
        self.encrypted_session_key = public_key.encrypt(self.session_key)

    def send_message(self, message):
        lol = pickle.dumps(message)
        self.socket.send(lol)
        pass

    def receive_message(self):
        return self.socket.recv(BUFFER_SIZE)

    def read_ca_public_key(self):
        with open(CA_PUBLIC_KEY_FILE, "r") as f:
            content = f.read()
        return content

    def get_public_key(self, public_key_content):
        return PKCS1_OAEP.new(RSA.importKey(public_key_content))

    def get_ca_public_key(self, public_key_content):
        return PKCS1_PSS.new(RSA.importKey(public_key_content))

    def receive_all_message(self):
        messages = ""

        while True:
            message = self.receive_message()
            if len(message) == 0:
                break
            messages += message

        return messages

    def decode_message(self, messages):
        message_list = messages.split(".")

        full_message = ""

        for message in message_list:
            if len(message) == 0:
                break
            real_message = pickle.loads(message + ".")
            full_message += self.aes.decrypt(real_message)

        return full_message

    def write_to_file(self, message):

        with open(OUTPUT_FILE, "w") as f:
            f.seek(0)
            f.truncate()
            f.write(message)

    def verify(self, name, public_key_content, signature, ca_public_key):
        md5 = MD5.new()
        md5.update(name)
        md5.update(public_key_content)
        return ca_public_key.verify(md5, signature)

    def connect(self):
        # receive bryan public key
        public_key_content = pickle.loads(self.receive_message())
        public_key = self.get_public_key(public_key_content)

        # receive signature
        signature = pickle.loads(self.receive_message())

        # get CA public key from file
        ca_public_key = self.get_ca_public_key(self.read_ca_public_key())

        if self.verify(RECEIVER_NAME, public_key_content, signature, ca_public_key):

            # encrypt session key
            self.encrypt_session_key(public_key)

            # send encrypted session key
            self.send_message(self.encrypted_session_key)

            # receive all message
            messages = self.receive_all_message()

            # get plaintext message
            messages = self.decode_message(messages)

            # write to file
            self.write_to_file(messages)

        else:
            print "Error:MD5 signature does not match"

        # close socket
        self.socket.close()