Search code examples
pythonsocketsencryptionaes

Data getting corrupted over aes file transfer python tkinter


I am working on a project where you can send a file over a socket and it is aes encrypted. And it works it encrypts the data and sends it over the socket and it decrypts it fine but the image is getting messed up below is the example of the before image and after how can I correct this?

Before: enter image description here

After: enter image description here

The encrypt and decrypt are in a separate module I created that is why they a referenced like they are below

Encryption and decryption code:

def encrypt(key, data, iv):
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    return encryptor.encrypt(data)

def decrypt(key, data, iv):
    decryptor = AES.new(key, AES.MODE_CBC, iv)
    return decryptor.decrypt(data)

Server Code:

s = socket.socket()
s.bind(("127.0.0.1", 5000))
s.listen(1)
c, addr = self.s.accept

name = c.recv(1024)
name = name.split("/")[-1]

newFile = open(self.curpath + name, "wb")
stop = False

while True:
    data = c.recv(24*1024)

    print(data[-4:])
    if data[-4:] == "DONE":
        break

    data = decrypt(self.key, data, self.iv)
    newFile.write(data)

    print("STOP")
    newFile.close()

Client Code:

s. = socket.socket()
s.connect(("127.0.0.1", 5000)

item = "Splash.png"
s.send(item)

with open(item, "rb") as fp:
        while True:
            chunk = fp.read(64*1024)

            if len(chunk) == 0:
                break
            elif len(chunk) % 16 != 0:
                chunk += " " * (16 - len(chunk) % 16)
            s.send(encrypt(self.key, chunk, self.iv))

s.send("DONE")
print("Done")

Solution

  • By using @t.m.adam comment I was able to get the software to run correctly using .rstrip(" ")