Ai
1 Star 0 Fork 0

eswindous/python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
通信4.py 1.79 KB
一键复制 编辑 原始数据 按行查看 历史
eswindous 提交于 2025-05-11 11:31 +08:00 . 实验2
import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
# 预共享密钥和初始化向量(必须与服务端一致)
key = b'abcdefghijklmnopqrstuvwxyz123456' # 32字节密钥
iv = b'1234567890abcdef' # 16字节初始化向量
def encrypt_file(file_path):
"""读取文件内容并加密"""
try:
with open(file_path, 'rb') as f:
plaintext = f.read()
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
return ciphertext
except Exception as e:
print(f"加密错误: {e}")
return None
def send_encrypted_file(server_ip, server_port, file_path):
"""连接服务器并发送加密文件"""
# 创建TCP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# 连接服务器
server_address = (server_ip, server_port)
client_socket.connect(server_address)
print(f"已连接到服务器 {server_ip}:{server_port}")
# 加密文件
encrypted_data = encrypt_file(file_path)
if encrypted_data:
# 发送加密数据
client_socket.sendall(encrypted_data)
print(f"已成功发送 {len(encrypted_data)} 字节的加密数据")
else:
print("加密失败,未发送数据")
except Exception as e:
print(f"发送过程中出错: {e}")
finally:
# 关闭连接
client_socket.close()
print("连接已关闭")
if __name__ == "__main__":
# 服务器地址和端口
server_ip = '192.168.1.100' # 请替换为实际服务器IP
server_port = 9999
# 要发送的文件路径
file_to_send = 'test.txt'
# 发送加密文件
send_encrypted_file(server_ip, server_port, file_to_send)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/eswindous/python.git
git@gitee.com:eswindous/python.git
eswindous
python
python
master

搜索帮助