1 Star 0 Fork 0

rukiTing/pythontest

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
s.py 1.91 KB
一键复制 编辑 原始数据 按行查看 历史
rukiTing 提交于 3个月前 . 实验3
import os
import socket
import random
from gmssl import sm4
#这里把端口单独领出来是因为上学期做实验的时候很容易出现端口占用的情况,放这容易改
PORT = 8081
MAXSIZE = 1024
#这里是设置了一个结束符,当client输入eixt的时候就结束通信
EXIT_SYMBOL = b"exit"
key = b"1234567890abcdef"
def decrypt_sm4(key, ctext):
"""使用SM4算法解密数据"""
crypt_sm4 = sm4.CryptSM4()
crypt_sm4.set_key(key, sm4.SM4_DECRYPT)
data = crypt_sm4.crypt_ecb(ctext)
return data
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#这里前面是地址,后面是端口,为了方便测试就把地址设为本机,127.0.0.0,0.0.0.0,localhost都是可以的
server_socket.bind(('0.0.0.0', PORT))
server_socket.listen(1)
print(f"Server is listening on port {PORT}...")
client_socket, client_address = server_socket.accept()
print("Client connected!")
try:
with open('file1.txt', 'r',encoding='utf-8') as file1, open('file2.txt', 'a',encoding='utf-8') as file2:
while True:
ctext = client_socket.recv(MAXSIZE)
print(f"server received:{ctext.hex()}")
if not ctext:
break
data = decrypt_sm4(key, ctext)
if data.startswith(EXIT_SYMBOL):
print("Received exit command from client.")
break
print(f"解密后的消息:{data.decode()}")
file2.write(data.decode())
file2.flush() # 强制将缓冲区的数据写入文件
file1.seek(0)
file1_content = file1.read(MAXSIZE - 1)
data_len = random.randint(1, len(file1_content))
client_socket.sendall(file1_content[:data_len].encode())
except Exception as e:
print(f"An error occurred: {e}")
finally:
client_socket.close()
server_socket.close()
print("Server closed.")
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/rukiting/pythontest.git
git@gitee.com:rukiting/pythontest.git
rukiting
pythontest
pythontest
test1

搜索帮助