144
社区成员




课程:《Python程序设计》
班级: 2212
姓名: 吕诗鹏
学号:20221219
实验教师:王志强
实验日期:2023年4月13日
必修/选修: 公选课
创建服务端和客户端,服务端在特定端口监听多个客户请求。客户端和服务端通过Socket套接字(TCP/UDP)进行通信。
1.导入加密DesModule模块
from pyDes import *
import binascii
def des_encrypt(s, KEY):
secret_key = KEY
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
en = k.encrypt(s, padmode=PAD_PKCS5)
return binascii.b2a_hex(en).decode()
def des_descrypt(s, KEY):
secret_key = KEY
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
return de.decode()
if __name__ == "__main__":
ciphertext = des_encrypt("hello, world!", "12345678")
print("密文:",ciphertext)
plaintext = des_descrypt(ciphertext, "12345678")
print("解密后的明文:", plaintext)
2.编写服务器程序
import socket
import os
from DesModule import *
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("192.168.1.133", 8000))
s.listen()
conn, address = s.accept()
data = conn.recv(1024)
ciphertext = des_encrypt("herllo", "11451419")
print("解密前", data.decode())
plaintext = des_descrypt(data, "81097581")
print("来自客户端的信息是", plaintext)
if os.path.exists("C:\\Users\\吕\\PycharmProjects\\pythonProject2\\lsp"):
file = open("lsp", 'a+')
file.write(plaintext)
else:
file = open("lsp", 'w+')
file.write(plaintext)
file.seek(0)
file.close()
conn.sendall(ciphertext.encode())
3.编写用户端程序
import socket
import os
from DesModule import *
if os.path.exists("C:\\Users\\吕\\PycharmProjects\\pythonProject2\\lsp"):
file1 = open("lsp", 'r+')
else:
file1 = open("lsp", 'w+')
file1.write("herllo")
file1.seek(0)
herllo = file1.readline()
ciphertext = des_encrypt(herllo, "11451419")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.168.1.112", 8000))
s.sendall(ciphertext.encode())
data = s.recv(1024)
print("解密前", data.decode())
plaintext = des_descrypt(data, "81097581")
print("从服务器接受的数据是:", plaintext)
file1.write(plaintext)
file1.close()
s.close()
4.运行结果
5.上传gitee
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
无