Ai
1 Star 0 Fork 0

Python程序设计/20191113-lzx

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
TPC_Client.py 2.72 KB
一键复制 编辑 原始数据 按行查看 历史
林紫欣 提交于 2020-05-17 13:12 +08:00 . TCP通信—2020年5月17日
# -*- coding: utf-8 -*-
'''
作者:20191113 林紫欣
文件名称:TCP通信——客户端
时间:2020年5月17日
'''
import time
import socket
import base64
from Crypto.Cipher import AES
CliSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serve_ip = input("Please enter the server IP:")
serve_port = int(input("Please enter the corresponding Port:")) # 端口要是int类型,所有要转换
CliSock.connect((serve_ip, serve_port)) # 连接服务器,建立连接,参数是元组形式
print('')
print('Hello! I am 20191113. \nWhat can I do for you?\nIf you want to encrypt a file, enter "encrypt file".\nTo end the chat, enter "quit".')
def send_out(filename):
with open(filename, 'rb') as file:
for i in file:
CliSock.send(i)
data = CliSock.recv(1024)
if data != b'success':
break
time.sleep(1)
CliSock.send('quit'.encode())
print("... File sent successfully ...")
def take_in(af_filename):
while True:
with open(af_filename, 'ab') as file:
data = CliSock.recv(1024)
if data == b'quit':
break
file.write(data)
time.sleep(1)
CliSock.sendall('success'.encode())
print("... File reception completed ...")
def add_to_16(value):# str不是16的倍数那就补足为16的倍数
while len(value) % 16 != 0:
value += '\0'
return str.encode(value) # 返回bytes
def decrypt(af_filename):
key = input('Please enter the corresponding key:')
text = str(open(af_filename, 'r').read()) # 密文文件
open(af_filename, 'r').close()
aes = AES.new(add_to_16(key), AES.MODE_ECB) # 初始化加密器
base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8')) # 优先逆向解密base64成bytes
decrypted_text = str(aes.decrypt(base64_decrypted), errors='ignore').replace('\0', '') # 执行解密
decrypted_text2 = eval(decrypted_text)
decrypted_text3 = decrypted_text2.decode('utf-8')
print("Successfully decrypted, the contents of the file are:")
print(decrypted_text3)
# 建立通讯循环
while True:
send_data = input("Enter your message:")
CliSock.send(send_data.encode('utf-8'))
time.sleep(1)
if send_data == 'quit':
print('\ncommunication ended.')
break
elif send_data == 'encrypt file':
filename = input("Please enter the file name:")
print("If the file is large, the run time will be a little long, please be patient.")
af_filename = 'Client encrypted.txt'
time.sleep(1)
send_out(filename)
take_in(af_filename)
decrypt(af_filename)
print('')
re = CliSock.recv(1024)
print("Server is sending:",re.decode('utf-8'))
CliSock.close()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/python_programming/lzx-20191113.git
git@gitee.com:python_programming/lzx-20191113.git
python_programming
lzx-20191113
20191113-lzx
newone

搜索帮助