Ai
1 Star 0 Fork 0

eswindous/python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
通信3.py 1.99 KB
一键复制 编辑 原始数据 按行查看 历史
eswindous 提交于 2025-05-11 11:31 +08:00 . 实验2
import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
# 预共享密钥和初始化向量(必须与客户端一致)
key = b'abcdefghijklmnopqrstuvwxyz123456' # 32字节密钥
iv = b'1234567890abcdef' # 16字节初始化向量
def decrypt_data(ciphertext):
"""解密接收到的数据"""
try:
cipher = AES.new(key, AES.MODE_CBC, iv)
decrypted_data = unpad(cipher.decrypt(ciphertext), AES.block_size)
return decrypted_data.decode('utf-8')
except Exception as e:
print(f"解密错误: {e}")
return None
# 创建TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口
server_address = ('0.0.0.0', 9999)
server_socket.bind(server_address)
# 开始监听
server_socket.listen(1)
print(f"服务器正在监听 {server_address[0]}:{server_address[1]}...")
try:
while True:
# 接受客户端连接
client_socket, client_address = server_socket.accept()
print(f"接受来自 {client_address} 的连接")
try:
# 接收加密数据
encrypted_data = b''
while True:
chunk = client_socket.recv(4096)
if not chunk:
break
encrypted_data += chunk
# 解密数据
decrypted_data = decrypt_data(encrypted_data)
if decrypted_data:
# 写入文件
with open('received_file.txt', 'w', encoding='utf-8') as f:
f.write(decrypted_data)
print("文件接收并解密成功,已保存为 received_file.txt")
else:
print("解密失败,未保存文件")
except Exception as e:
print(f"处理客户端请求时出错: {e}")
finally:
# 关闭客户端连接
client_socket.close()
except KeyboardInterrupt:
print("\n服务器关闭中...")
finally:
# 关闭服务器套接字
server_socket.close()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/eswindous/python.git
git@gitee.com:eswindous/python.git
eswindous
python
python
master

搜索帮助