通过套接字发送加密数据并解密不起作用

Sending Encrypted Data Through Socket And Decrypting Doesn't Work

我正在创建一个简单的加密软件。我目前遇到的问题是通过套接字发送加密的 aes 文件数据不起作用。在接收端,应该写入的文件是空的。我已经仔细查看了我的代码一段时间,但无法解决它。

我做了一个没有联网的版本。 我已经能够在不同版本上发送最大 8 KB 的小文件

我的程序是基于功能的,所以程序从主菜单分支到其他菜单和功能。既然有点跳,最好把所有代码都展示出来。 https://github.com/BaconBombz/Dencryptor/blob/Version-2.0/Dencryptor.py

套接字已连接,所有需要的数据已发送。然后,文件经过 AES 加密并通过套接字发送。接收端将加密数据写入文件并解密。程序会说文件已发送,但在接收端,程序会吐出一个结构错误,因为应该包含加密数据的文件是空的。

代码太非minimal所以这里是下载未加密文件的最小示例。此外,TCP 是一种流式传输协议,使用睡眠来分隔数据是不正确的。而是为字节流定义一个协议。这是我的示例的协议:

  1. 打开连接。
  2. 发送 UTF-8 编码的文件名,后跟换行符。
  3. 以十进制发送编码后的文件大小,后跟一个换行符。
  4. 发送文件字节。
  5. 关闭连接。

注意Python 3 代码。 Python 2 对我来说已经死了。支持将于明年结束,所以请升级!

server.py

from socket import *
import os

CHUNKSIZE = 1_000_000

# Make a directory for the received files.
os.makedirs('Downloads',exist_ok=True)

sock = socket()
sock.bind(('',5000))
sock.listen(1)

with sock:
    while True:
        client,addr = sock.accept()

        # Use a socket.makefile() object to treat the socket as a file.
        # Then, readline() can be used to read the newline-terminated metadata.
        with client, client.makefile('rb') as clientfile:
            filename = clientfile.readline().strip().decode()
            length = int(clientfile.readline())
            print(f'Downloading {filename}:{length}...')
            path = os.path.join('Downloads',filename)

            # Read the data in chunks so it can handle large files.
            with open(path,'wb') as f:
                while length:
                    chunk = min(length,CHUNKSIZE)
                    data = clientfile.read(chunk)
                    if not data: break # socket closed
                    f.write(data)
                    length -= len(data)

            if length != 0:
                print('Invalid download.')
            else:
                print('Done.')

client.py

from socket import *
import os

CHUNKSIZE = 1_000_000

filename = input('File to upload: ')

sock = socket()
sock.connect(('localhost',5000))
with sock,open(filename,'rb') as f:
    sock.sendall(filename.encode() + b'\n')
    sock.sendall(f'{os.path.getsize(filename)}'.encode() + b'\n')

    # Send the file in chunks so large files can be handled.
    while True:
        data = f.read(CHUNKSIZE)
        if not data: break
        sock.sendall(data)