代码拉取完成,页面将自动刷新
# -*- 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()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。