Esempio n. 1
0
def generate_token(user):
    """
        token contains: (generated session key, expiry date) encrypted with system wide shared secret
        ticket contains: ((generated session key), (generated session key, expiry date)) encrypted 
            with clients public key
    """

    expiry_date = (datetime.datetime.now() +
                   datetime.timedelta(minutes=10)).timestamp()

    token = {"gen_session_key": " ", "expiry_date": expiry_date}
    token_serialised = json.dumps(token, cls=DateTimeEncoder)

    cipher = AESCipher(SHARED_SECRET)
    encode_hash_session_key = cipher.encrypt(token_serialised)

    ticket = json.dumps({
        'gen_session_key': user['gen_session_key'],
        'token': encode_hash_session_key
    })

    # encrypting the whole ticket with client's password or public key
    cipher = PKCS1_OAEP.new(user['public_key'])
    encode_hash_ticket = cipher.encrypt(str.encode(ticket))
    return encode_hash_ticket
Esempio n. 2
0
    def __init__(self, file_path, enc_key):
        self.Path = os.path.abspath(file_path)
        if not os.path.exists(self.Path):
            sys.exit('File does not exist!')
        if not os.path.isfile(self.Path):
            sys.exit(self.Path + ' - is not file!')

        try:
            file = open(file_path, 'rb')
        except Exception:
            sys.exit('Can not open file!')

        try:
            self.File_bytes = file.read()
        except Exception:
            sys.exit('Can not read file!')

        self.File_name = os.path.basename(self.Path)

        file_name_bytes = self.File_name.encode()

        if len(file_name_bytes) > 255:
            sys.exit('File name is too long!')

        self.File_name_len = bytes([len(file_name_bytes)])

        self.Hash_sum = hashlib.md5(self.File_bytes).hexdigest()

        byte_string = self.Hash_sum.encode() \
            + self.File_name_len \
            + file_name_bytes \
            + self.File_bytes

        cipher = AESCipher(enc_key)

        self.Encrypted_file = cipher.encrypt(byte_string.decode())

        # The maximum number that is placed in the block
        self._max_enc_file_size = 9999999999999999999999999999999

        size_enc_file = len(self.Encrypted_file)
        if size_enc_file > self._max_enc_file_size:
            sys.exit('File too large!')
        self.Encrypted_size = cipher.encrypt(str(size_enc_file))

        self.Finally_byte_string = self.Encrypted_size + self.Encrypted_file

        self.Finally_size = len(self.Finally_byte_string)

        self.Binary_string = self.get_binary_string()

        file.close()
Esempio n. 3
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. 4
0
 def encrypt_payload(self, decrypted_payload, user_id):
     aeskey = self.get_token(user_id)
     aesiv = self.get_iv(user_id)
     aesc = AESCipher(aeskey)
     aesc.set_iv(aesiv)
     encrypted_bytes = aesc.encrypt(decrypted_payload)
     return encrypted_bytes
Esempio n. 5
0
    def process_outgoing_message(self, msg_raw, originates_from_console=False):
        '''
        Process an outgoing message before Base64 encoding

        :param msg_raw: raw message
        :return: message to be sent to the server
        '''

        # if the message has been typed into the console, record it, so it is never printed again during chatting
        if originates_from_console == True:
            self.update_send_ctr()
            # message is already seen on the console
            cipher = AESCipher(self.symm_key)
            encrypted_msg = cipher.encrypt(msg_raw)

            str_to_sign = MESSAGE_CODE + '|' + encrypted_msg + '|' + str(
                self.send_counter)
            sig = self.sign(str_to_sign)
            msg_raw = str_to_sign + '|' + sig
            m = Message(owner_name=self.manager.user_name, content=msg_raw)
            self.printed_messages.append(m)

        # process outgoing message here
# example is base64 encoding, extend this with any crypto processing of your protocol
        encoded_msg = base64.encodestring(msg_raw)

        # post the message to the conversation
        self.manager.post_message_to_conversation(encoded_msg)
Esempio n. 6
0
 def encrypt_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)
     encrypted_bytes = aesc.encrypt(pkt)
     return encrypted_bytes
Esempio n. 7
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. 9
0
 def encrypt_file(self, file_name):
     aes = AESCipher(self.key)
     with open(file_name, 'rb') as file:
         text = file.read()
     enc = aes.encrypt(text)
     with open(file_name, 'wb') as file:
         file.write(enc)
Esempio n. 10
0
File: api.py Progetto: bebound/Pixiv
 def save_session(self):
     data = {
         'username': self.username,
         'passwd': self.password
     }
     cipher = AESCipher()
     enc = cipher.encrypt(json.dumps(data))
     with open('session', 'wb') as f:
         f.write(enc)
Esempio n. 11
0
 def save_session(self):
     data = {
         'username': self.username,
         'passwd': self.password
     }
     cipher = AESCipher()
     enc = cipher.encrypt(json.dumps(data))
     with open('session', 'wb') as f:
         f.write(enc)
Esempio n. 12
0
 def save_session(self):
     data = {
         'access_token': self.access_token,
         'refresh_token': self.refresh_token
     }
     cipher = AESCipher()
     enc = cipher.encrypt(json.dumps(data))
     with open('session', 'wb') as f:
         f.write(enc)
Esempio n. 13
0
def save(key, entries):
    """ Encrypt the passwords we stored in RAM and write them to the database """
    db = Database()
    cipher = AESCipher(key)
    tmp = []
    for entry in entries:
        entry_2 = cipher.encrypt(entry[2])
        tmp.append([entry[0], entry[1], entry_2.decode()])
    # Write the encrypted passwords to the database
    if (db.update(tmp)):
        print_error("Couldn't save")
Esempio n. 14
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)
Esempio n. 15
0
    def serverSend(self):
        sessionCipher = AESCipher(str(self.sessionKey))
        while True:
            try:
                reply = raw_input('')
                message = sessionCipher.encrypt(reply)

                print '\n############## NOW SENDING MESSAGE ############'
                print 'Sending encrypted message:', message.encode('hex')
                self.clientSock.send(message)
                print '############## MESSAGE SENT ###################\n'
            except KeyboardInterupt:
                print 'Exiting'
                self.clientSock.close()
                self.sock.close()
                sys.exit(1)
Esempio n. 16
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. 17
0
def save_wallet(wallet):
    password1 = getpass.getpass(
        'Enter the password to encrypt the hot wallet: ')
    password2 = getpass.getpass(
        'Re-enter the password to encrypt the hot wallet: ')

    if password1 != password2:
        print('Passwords do not match!', file=sys.stderr)
        sys.exit(1)

    cipher = AESCipher(key=password1)
    unencrypted_data = bytes(
        simplejson.dumps(wallet, sort_keys=True, indent=4), 'utf-8')

    with open(os.path.join(WALLET_DIR, '%s.enc' % WALLET_ID),
              'w') as output_file:
        output_file.write(str(cipher.encrypt(unencrypted_data), 'utf-8'))
Esempio n. 18
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. 19
0
    def sendMessage(self):
        #generate cipher for session
        sessionCipher = AESCipher(str(self.sessionKey))

        print 'VPN Connected'
        while True:
            try:
                #prompt client for message
                dataCl = raw_input('')

                #encrypt message
                cipherText = sessionCipher.encrypt(dataCl)

                print '\n############## NOW SENDING MESSAGE ############'
                print 'Sending encrypted message:', cipherText.encode('hex')
                print '############## MESSAGE SENT ###################\n'

                #send message to server
                self.send(cipherText)

            except:
                print 'Exiting'
                self.close()
                sys.exit(1)
Esempio n. 20
0
from AESCipher import AESCipher

content = open('paragraph.txt', 'r').read()

# cipher1 = AESCipher('mysecretpassword')
# encrypted = cipher1.encrypt(string)
# cipher2 = AESCipher('mysecretpassword')
# decrypted = cipher2.decrypt(encrypted)
# print(encrypted)
# print(decrypted)

cipher1 = AESCipher('mysecretpassword')
cipher2 = AESCipher('mysecretpassword')
encrypted = cipher1.encrypt(content)
# decrypted = cipher2.decrypt(encrypted)

with open('paragraph-compressed-encrypted.bin', 'wb') as file:
	file.write(encrypted)
	file.close()
Esempio n. 21
0
encrpyt_mapping = []
for col in columns_to_encrypt:
    encrpyt_mapping.append(col)
    encrpyt_mapping.append(str(col) + " encrypted_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 index, row in data.iterrows():
        # i = 0
        # print(index)
        for col in columns_to_encrypt:
            if isinstance(row[col], float):
                if math.isnan(row[col]):
                    row[col] = str(row[col])
                else:
                    row[col] = int(row[col])
            encoded = cypher_obj.encrypt(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 "Encrypting of data in csv file %s is completed" % csv_file
    print "Writing CSV file for encrypted data"
    data.to_csv(os.path.join(csv_dir, "enc_" + csv_file), encoding='utf-8')
    # mapping_df.to_csv(os.path.join(csv_dir, "mapping_" + csv_file), encoding='utf-8')
Esempio n. 22
0
        soundProcessing(filename_no_ext)
    #Creating key for encryption
    key = ''
    for note in detected_notes:
        key += note
    aes = AESCipher(key)
    if (opMode == 'E'):  #Encryption
        if (opType == 'T'):  #Text mode
            if (isInteractive):
                opData = input('(6/6) Text to encrypt?: ')
            print(
                f'Encrypted text: {aes.encrypt(opData.encode(),encode=True)}')
        else:  #File mode
            if (isInteractive):
                opData = input('(6/6) File to encrypt?: ')
            encryptedData = aes.encrypt(readBinFile(opData), encode=False)
            writeBinToFile(encryptedData, f'{opData}.aenc')
    else:
        if (opType == 'T'):  #Text mode
            if (isInteractive):
                opData = input('(6/6) Text to decrypt?: ')
            print(
                f'Decrypted text: {aes.decrypt(opData,decode=True).decode()}')
        else:  #File mode
            if (isInteractive):
                opData = input('(6/6) File to decrypt?: ')
            decryptedData = aes.decrypt(readBinFile(opData), decode=False)
            writeBinToFile(decryptedData,
                           opData[0:len(opData) -
                                  5])  #Binary write deleting aenc extension
Esempio n. 23
0
class RubLogin(QMainWindow):
    def __init__(self):
        """ Initialize ui. Connect ui elements to functions. Initialize LoginAgent """
        super(RubLogin, self).__init__()
        uic.loadUi('design.ui', self)
        self.pushButton_login.clicked.connect(self.login)
        self.pushButton_logout.clicked.connect(self.logout)
        self.checkBox_auto.clicked.connect(self.checkBoxAuto)
        self.checkBox_save.clicked.connect(self.checkBoxSave)
        self.checkBox_auto_onstartup.clicked.connect(
            self.checkBoxAutoOnStartup)
        self.loginAgent = LoginAgent(self.textArea_log,
                                     self.checkBox_fileLogging, self.statusBar)
        self.guiEnabled = True

        aes_key = "Jgj-4f;5$f-d.kg&ghkDe-Fg&kSgZ5pd"
        self.aesCipher = AESCipher(aes_key)

        if len(sys.argv) > 1:
            for x in sys.argv:
                if x == "-nogui":
                    self.guiEnabled = False

        # TODO comment
        try:
            data_file = open("data.bin", "rb")
            self.checkBox_fileLogging.setChecked(pickle.load(data_file))
            self.checkBox_auto.setChecked(pickle.load(data_file))
            self.checkBox_save.setChecked(pickle.load(data_file))
            self.checkBox_auto_onstartup.setChecked(pickle.load(data_file))
            if self.checkBox_save.isChecked():
                self.lineEdit_id.setText(
                    self.aesCipher.decrypt(pickle.load(data_file),
                                           pickle.load(data_file)))
                self.lineEdit_pass.setText(
                    self.aesCipher.decrypt(pickle.load(data_file),
                                           pickle.load(data_file)))
            elif not self.guiEnabled:
                data_file.close()
                self.cl_exit("No login data saved")
            data_file.close()
        except (FileNotFoundError, EOFError):
            if not self.guiEnabled:
                self.cl_exit("No login data saved")

        if self.guiEnabled:
            # systemtray icon
            self.trayIcon = SystemTrayIcon(QtGui.QIcon("logo.png"), self)
            self.show()

        if self.checkBox_auto_onstartup.isChecked():
            self.checkBox_auto.setChecked(True)
            self.login()

    def cl_exit(self, msg):
        print(msg)
        sys.exit(0)

    def login(self):
        """ Initiate login: Collect information from ui elements and start the login agent """

        loginID = self.lineEdit_id.text()
        pwd = self.lineEdit_pass.text()

        if self.checkBox_auto.isChecked():
            res = self.loginAgent.autoLogin(loginID, pwd)  # auto login
        else:
            res = self.loginAgent.login(loginID, pwd, None, False)  # login

        self.statusBar().showMessage(
            "Login succeeded" if res else "Login failed")

        data_file = open("data.bin", "wb")

        pickle.dump(self.checkBox_fileLogging.isChecked(), data_file)
        pickle.dump(self.checkBox_auto.isChecked(), data_file)
        if res and self.checkBox_save.isChecked():
            pickle.dump(self.checkBox_auto_onstartup.isChecked(), data_file)
            pickle.dump(self.checkBox_save.isChecked(), data_file)
            [enc_id, iv_id] = self.aesCipher.encrypt(loginID)
            [enc_pwd, iv_pwd] = self.aesCipher.encrypt(pwd)
            pickle.dump(enc_id, data_file)
            pickle.dump(iv_id, data_file)
            pickle.dump(enc_pwd, data_file)
            pickle.dump(iv_pwd, data_file)
        elif not res and self.checkBox_save.isChecked():
            pickle.dump(False,
                        data_file)  # uncheck checkBox_save on login fail

        data_file.close()

        return res

    def logout(self):
        """ Clean up and logout """
        self.loginAgent.logout()

    def closeEvent(self, event):
        """ Clean up for when program is exited """
        self.loginAgent.stopLoginDaemon()
        event.accept()

    def checkBoxAuto(self):
        """ If the checkbox is unchecked by user, cancel the running auto login """
        if not self.checkBox_auto.isChecked():
            self.loginAgent.stopLoginDaemon()

    def checkBoxAutoOnStartup(self):
        if self.checkBox_auto_onstartup.isChecked():
            self.checkBox_save.setChecked(True)

    def checkBoxSave(self):
        if not self.checkBox_save.isChecked():
            self.checkBox_auto_onstartup.setChecked(False)

    def keyPressEvent(self, event):
        """
		handle key press events:
		ENTER - does the same as clicking the login button
	    """
        if event.key() == QtCore.Qt.Key_Return or event.key(
        ) == QtCore.Qt.Key_Enter:
            # TODO
            pass

    def changeEvent(self, event):
        print("ChangeEvent!")
        # check if loginAgent was already instantiated in this class and if the auto login is running
        if hasattr(
                self, "loginAgent"
        ) and self.loginAgent is not None and self.loginAgent.is_auto_login_running(
        ):
            if event.type() == QEvent.WindowStateChange:
                # detect the window minimized event
                if self.windowState() & Qt.WindowMinimized:
                    # show system tray icon, display notification, hide main window
                    self.trayIcon.show()
                    self.trayIcon.showMessage(
                        self.windowTitle(),
                        "Auto login is running in the background",
                        QtWidgets.QSystemTrayIcon.Information, 5000)
                    self.hide()
Esempio n. 24
0
class MessagesFunctions(object):
    def __init__(self):
        self.file_number = 0
        self.encryption_suite = AESCipher()

    def get_enc_message(self, message_length, client_socket):
        """
        :param client_socket: the client socket.
        :param message_length: the length of the message the was received.
        :return: the message.
        """
        try:
            message = self.get_message_content(message_length, client_socket)
            if message.find(IMAGE_SUFFIX) != -1:
                return self.encryption_suite.decrypt_image(
                    message[:-len(IMAGE_SUFFIX)])
            decrypted_message = self.encryption_suite.decrypt(message)
            if decrypted_message[-1:] == PICKLE_BIT:
                return pickle.loads(decrypted_message)

            return message
        except Exception:
            pass

    @staticmethod
    def get_message_content(message_length, client_socket):
        content = ""
        while (len(content) != message_length):
            content += client_socket.recv(message_length - len(content))
        return content

    @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))
        try:
            return int(message_length)
        except ValueError:
            pass

    def receive_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)
        message = self.get_enc_message(message_length, client_socket)
        return message

    def get_file(self, file_suffix, client_socket):
        """
        :param file_suffix: the suffix of the original file (exm: .txt, .docx).
        :param client_socket: the socket to receive data from.
        """
        # TODO check whether a file + number is already exists.
        self.file_number += 1
        file_length = self.get_message_length(client_socket)
        file_data = self.get_message_content(file_length, client_socket)
        pickled_file = ''
        try:
            pickled_file = pickle.loads(file_data)
        except (KeyError, IndexError, ValueError, ImportError):
            pass

        if isinstance(pickled_file, FileNotExists):
            wx.CallAfter(
                wx.GetApp().chat_frame.main_panel.chat_log.new_text_message,
                FileNotExists())
        else:
            f = open(
                FILES_FOLDER + DEFAULT_FILE_NAME + str(self.file_number) +
                file_suffix, WRITE_BIN_MODE)
            f.write(file_data)
            f.close()

    def send_file(self, file_path, client_socket):
        """
        @param file_path: the file's path in the sender's pc.
        @param client_socket: the socket of the sender.
        the function sends a file over the files socket.
        """
        try:
            print '- - - - Sending File - - - -'
            f = open(file_path, READ_BIN_MODE)
            print '[1] opened file'
            file_content = f.read()
            print '[2] read file data'
            client_socket.send(str(len(file_content)).zfill(LEN_OF_LENGTH))
            print '[3] send file data length'
            time.sleep(0.1)
            client_socket.send(file_content)
            print '[4] send file data'
            f.close()
            print '[5] closed file'
        except IOError:
            self.send_message(FileNotExists(), True, client_socket)
            print '[-1] file not exists'

    def send_enc_message(self, message, to_pickle, client_socket):
        """
        :param message: the message that will be sent(as its encrypted form).
        :param to_pickle: a boolean the means rather to pickle the message or not to.
        :param client_socket: the socket to sent the message from.
        """
        if to_pickle:
            message = pickle.dumps(message) + PICKLE_BIT
        if message.find(IMAGE_SUFFIX) != -1:
            encrypted_message = self.encryption_suite.encrypt_image(
                message[:-len(IMAGE_SUFFIX)])
        else:
            encrypted_message = self.encryption_suite.encrypt(message)

        client_socket.send(str(len(encrypted_message)).zfill(LEN_OF_LENGTH))
        client_socket.send(encrypted_message)

    @staticmethod
    def send_message(message, to_pickle, client_socket):
        if to_pickle:
            message = pickle.dumps(message) + PICKLE_BIT

        client_socket.send(str(len(message)).zfill(LEN_OF_LENGTH))
        client_socket.send(message)
Esempio n. 25
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)
class Package:
    def __init__(self):
        # Load config
        with open('config_client.json', 'r') as fp:
            config_vars = json.load(fp)

        self.HOST = config_vars['host']
        self.PORT = config_vars['port']
        self.SIZE = config_vars['size']
        self.KEY = config_vars['aeskey']
        self.BS = config_vars['blocksize']
        self.ENCRYPTOR = AES(self.KEY, self.BS)
        # TODO: read from config or constructor
        # For now hard-coding to a door package
        self.pkg_type = 1  # 1 if door, 0 if window

    def wrap_payload(self, payload, encrypted=True):
        header_title = 0x00

        if self.pkg_type == 1:
            header_title = header_title | 0x04

        if encrypted:
            header_title = header_title | 0x02

        # Payload is an update
        if isinstance(payload, str):
            payload = payload.encode()

        # Payload is an image
        elif isinstance(payload, Image.Image):
            header_title = header_title | 0x01
            payload = np.array(payload.convert('L'))
            image_w, image_h = payload.shape
            payload = payload.flatten()

            # Payload sanity testing
            for elem in payload:
                if not isinstance(elem, np.uint8):
                    raise TypeError("Payload values must be uint8")
                elif -1 > elem > 255:
                    raise ValueError(
                        "Payload values must be in range of [0, 255]")
            payload = image_w.to_bytes(2, 'big') + image_h.to_bytes(
                2, 'big') + bytes(payload)
        else:
            raise TypeError("Payload type is invalid")

        # Encryption
        if encrypted:
            payload = self.ENCRYPTOR.encrypt(payload)

        if len(payload) & 0xFFFFF != len(payload):
            raise ValueError("Payload size cannot fit in 20 bits")

        # header = bytes([header_title]) + (len(payload).to_bytes(3, 'big'))
        header = (header_title << 20) | (len(payload))
        header = header.to_bytes(3, 'big')

        return header + payload

    def start(self):
        print("Starting client")

        # Connecting to server
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((self.HOST, self.PORT))
            print("Connected to {0}:{1}".format(self.HOST, self.PORT))

            # Initialisation
            pass  # TODO

            # Communication loop
            # Getting user input
            print('> ', end='')
            t = str(input())

            i = Image.open("sample_image.png")

            # Exit Condition
            if t == 'exit':
                exit()

            # Send message
            # Send update
            # s.sendall(self.wrap_payload(t))

            # Send image
            wrappedPayload = self.wrap_payload(i)
            s.sendall(len(wrappedPayload).to_bytes(4, byteorder='big'))
            s.sendall(wrappedPayload)

            # Receive response
            # data = s.recv(self.SIZE)

            # Act on response data
            # print(data.decode())

        print('Quitting Client')
Esempio n. 27
0
                        alicePublicKey = int(alicePublicKey)

                        dhBob = DiffieHellman(g, p, alicePublicKey)
                        toSend['header'] = 'DH'
                        toSend['data'] = str(dhBob.publicKey)
                        print('Bob SharedSecret(%d): %d' %
                              (dhBob.sharedSecret.bit_length(),
                               dhBob.sharedSecret))
                        aesOBJ = AESCipher(str(dhBob.sharedSecret))
                    else:
                        print('DIGITAL SIGNATURE NOT VERIFIED!')
                elif header == "AES":
                    decryptedBody = aesOBJ.decrypt(body)
                    print("RESPONSE: %s" % decryptedBody)
                    inpt = input('Your message > ')
                    enc = aesOBJ.encrypt(inpt)
                    toSend['header'] = 'AES'
                    toSend['data'] = enc

                else:
                    toSend['header'] = ''
                    toSend['data'] = ''
                    break

                connection.sendall(pickle.dumps(toSend))
            else:
                print('no more data from', client_address)
                break

    finally:
        # Clean up the connection
Esempio n. 28
0
def encryptAES(decrypted, key):
    encryptor = AESCipher(key)
    encrypted = encryptor.encrypt(decrypted)
    return encrypted
Esempio n. 29
0
 def encrypt_password(self, host):
     cipher = AESCipher(base64.decodestring(host['key']))
     return cipher.encrypt(host['password'])
Esempio n. 30
0
if (len(sys.argv) < 2):
    print "need a filename"
    exit(1)

inputname = sys.argv[1]

passPhraseName= "MyPhraseName"
passPhrase = "rosebud"

#obtain cleartext
fh = open(inputname)
if (fh == None):
    print "bad filename"
    exit(1)

cleartext = 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)
ciphertext = aes.encrypt(cleartext)

#truncate file if it exists
outfile = open("{0}.{1}".format(inputname,passPhraseName),'w+')
outfile.write(ciphertext) 
outfile.close()
print "Completed"
Esempio n. 31
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. 32
0
 def encrypt_password(self, host):
     cipher = AESCipher(base64.decodestring(host['key']))
     return cipher.encrypt(host['password'])
Esempio n. 33
0
conn, addr = sock.accept()

# sends public key and signature
pub = public_key.exportKey()
conn.send(pickle.dumps(pub))
conn.send(pickle.dumps(signature))
print("Public key and signature sent.")

# reads session password
key = pickle.loads(conn.recv(1024))

#decrypt the password
rsa = PKCS1_OAEP.new(private_key)
key = rsa.decrypt(key)

# create an AES key using the password
cipher = AESCipher(key)
print("Session key obtained.")

# opens the text file for reading
with open("docs.txt", "r") as f:
    for line in f:
        # encrypt the line
        enc = cipher.encrypt(line)
        # pickle and send it
        conn.send(pickle.dumps(enc))

conn.close()
print("Document send.")
Esempio n. 34
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. 35
0
class Blockchain:
    def __init__(self):
        self.blocks = []

        key_for_md5_aes = '#TCC2019-N2N#'
        self.aes = AESCipher(key_for_md5_aes)

        # Carregando com paramêtros de acesso para desenvolvedor
        usuario_banco = urllib.parse.quote_plus('dev_connect')
        senha_banco = urllib.parse.quote_plus('rgPuzhTgc8HAHFlV')

        # Criando conexão com o MongoDB
        conexao_servidor = MongoClient(
            'mongodb+srv://%s:%[email protected]/?retryWrites=true'
            % (usuario_banco, senha_banco))

        # Instanciando um gerenciador do banco de dados TCC
        self.conexao_bd = conexao_servidor.TCC

        self.set_genesis_block()

    def set_genesis_block(self):
        first_transaction = [{"tipo_log": "log_inicial"}]

        self.hash_block_and_send(first_transaction)

    def hash_block_and_send(self, transactions):
        transactions = self.aes.encrypt(transactions)

        timestamp = datetime.utcnow().timestamp()
        prev_hash = self.get_last_hash()
        index = self.get_blockchain_length()

        block_formatted = {
            'transactions': transactions,
            'timestamp': timestamp,
            'prev_hash': prev_hash,
            'index': index
        }

        block_string = '{}'.format(block_formatted)

        datatime = datetime.now().strftime("%d/%m/%Y, %H:%M:%S")

        hash = sha256(block_string.encode()).hexdigest()

        self.blocks.append(hash)

        self.conexao_bd.HBase.insert(block_formatted)

        print("\n bloco criado às " + datatime + " " + str(timestamp))

    def add_new_block(self, transactions):
        self.hash_block_and_send(transactions)

    def get_last_hash(self):
        return self.blocks[-1] if (len(self.blocks) > 0) else "initial"

    def get_blockchain_length(self):
        return len(self.blocks)

    # def is_hash_valid(self,hash):
    #     return hash.startswith('0000')

    def get_all(self):
        return self.blocks[:]
Esempio n. 36
0
conn, addr = sock.accept()

# sends public key and signature
pub = public_key.exportKey()
conn.send(pickle.dumps(pub))
conn.send(pickle.dumps(signature))
print("Public key and signature sent.")

# reads session password
key = pickle.loads(conn.recv(1024))

#decrypt the password
rsa = PKCS1_OAEP.new(private_key)
key = rsa.decrypt(key)

# create an AES key using the password
cipher = AESCipher(key)
print("Session key obtained.")

# opens the text file for reading
with open("docs.txt", "r") as f:
	for line in f:
		# encrypt the line
		enc = cipher.encrypt(line)
		# pickle and send it
		conn.send(pickle.dumps(enc))

conn.close()
print("Document send.")
Esempio n. 37
0
print('Socket is listening')



while True:

    c, addr = s.accept()
    #sends certificate 
    c.send(certificate)

    cipher = AESCipher(key)

    #receives encrypted information if certificate is valid
    client_message = c.recv(128)
    updated_message = client_message.decode('utf-8')
    if updated_message == 'goodbye':
        print(updated_message)
        c.close()
    
    else:
        #decrypts information
        decrypted_message = cipher.decrypt(client_message)
        print(decrypted_message)

        c.send(cipher.encrypt('We sure do.'))

        c.close()