Считать двоичный файл, зашифровать строку, отправить ее через сокеты и расшифровать, записать в двоичный файл в файл в Python 3? - PullRequest
0 голосов
/ 21 октября 2018

Client.py

from socket import *
from threading import Thread

from Crypto.Cipher import AES

# f is for opening the file and reading the binary data
# that I later want to send to another client
f = open('book.epub', 'rb')

# f2 is to see if there is anything wrong with my method of writing
# So I open the file f2 in 'wb' mode and later encrypt everything I read
# from f and then decrypt it so that I can see if the encryption /
# decryption method changes any of the bytes
f2 = open('example.epub', 'wb')


# Used to encrypt messages
def encrypting(message):
    obj = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
    ciphertext = obj.encrypt(message)
    return ciphertext


# Used to decrypt messages
def decrypting(ciphertext):
    obj2 = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
    message = obj2.decrypt(ciphertext)
    return message


def main():
    s = socket()
    s.connect(('localhost', 15000))
    # Now I'm connected to the localhost at port 15000

    # Reads 512 charactes of file "f" and
    # Make data equal those characters
    data = f.read(512)

    # While data that I'm reading is not empty, write data to file f2
    # and encrypt it so it can be securely sent
    # When I've read the whole file "f", the data variable becomes empty
    # And the while loop ends
    while data:
        data = encrypting(data)
        data = decrypting(data)

        # I do an encryption and decryption to make sure
        # That there is nothing wrong with the process.
        # If I can't open the file "f2" after the program is done
        # then I can't possibly open the file I just send to another
        # computer, so I just double check
        print('Writing data: ' + str(data))
        f2.write(data)

        # Encrypts data after making sure that the data
        # Is not mangled during encryption / decryption 
        data = encrypting(data)
        # Sending encrypted data to server
        s.send(data)

        # Reading the next 512 characters of file f
        data = f.read(512)

# Closing all the open streams
s.close()
f.close()
f2.close()


if __name__ == '__main__':
    main()

Server.py

from socket import *
from threading import Thread

from Crypto.Cipher import AES

# Opening file "fi", which is the file I will be writing
# All the binary data I've received from the client
fi = open('trash.epub', 'wb')


# Used to encrypt the data
def encrypting(message):
    obj = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
    ciphertext = obj.encrypt(message)
    return ciphertext


# Used to decrypt the received data
def decrypting(ciphertext):
    obj2 = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
    message = obj2.decrypt(ciphertext)
    return message


def client_handler():
    conn, addr = s.accept()
    print(str(addr) + ' connected!')

    # Continues until data is empty
    while True:
        # Listens and receives a whopping 4096 
        data = conn.recv(4096)

        # Breaks is data send is empty
        # Client send empty data when reading past the file lengt
        # Hence the file reading and sending is complete
        if data == b'':
            conn.close()
            break

        # Decrypting the encrypted data
        data = decrypting(data)

        # Printing the data the program is about to write
        # As well as it's type, just for debug purposes
        print('Writing: ' + str(data) + '\n\n')
        print('Type: ' + str(type(data)))

        # Writes the decrypted binary data received from the client
        fi.write(data)

    # Closes streams
    fi.close()
    s.close()


HOST = "localhost"
PORT = 15000


# Initializing the server on
# the address: localhost
# and the port: 15000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(4)

print("Server is runnig")

# Executes the client_handler(), which listens to incoming data
client_handler()

Когда я пытаюсь открыть trash.epub с помощью mupdf (я нахожусь в Arch Linux), я получаю сообщение об ошибке::

error: zlib inflate error: invalid distance too far back

Файлы book.epub и example.epub работают без проблем, но trash.epub - это просто ... мусор.Файл «trash.epub» имеет тот же размер файла, что и два других.Когда я ввожу

nano book.epub

При вводе nano trash.epub обнаруживаются те же данные, такое же количество строк, одинаковое количество символов. Тем не менее, я не могу открыть trash.epub.Я могу открыть example.epub без проблем, но что-то не так с trash.epub.Есть идеи?

...