如何通过TCP插座中的Internet发送加密文件Python 3
我正在尝试通过Python的TCP插座发送加密文件,我不想加密消息,将其保存在%temp%然后发送(可以填充硬盘驱动器空间)中。 I am following this code I found online at: https://gist.github.com/giefko/2fa22e01ff98e72a5be2< /a>
这是我的服务器代码:
from random import choice
import socket, os, threading, json
from cryptography.fernet import Fernet
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPWRSTUVWXYZ1234567890!@#$%^&*()"
#read the key or generate
key = b""
if os.path.exists("client.key"):
with open("client.key", "rb") as f:
key = f.read()
else:
with open("client.key", "wb") as f:
key = Fernet.generate_key()
f.write(key)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 34467
host = "0.0.0.0"
s.bind((host, port))
print(f"LISTENING ON {host}:{port}")
s.listen(100)
def new_salt():
salt = ""
for x in range(15):
salt += choice(chars)
return salt
def handle_client(conn, addr):
encryption = False
def send_raw(content_type, Bytes_, salt=new_salt()):
seperator = "<|SEPERATE|>"
to_send = content_type + seperator + Bytes_.decode() + seperator + salt
to_send = to_send.encode()
if encryption:
to_send = Fernet(key).encrypt(to_send)
conn.send(to_send)
def recv_raw(BufferSize):
seperator = "<|SEPERATE|>".encode()
data = b""
while True:
data = conn.recv(BufferSize)
if data: break
if encryption:
data = Fernet(key).decrypt(data)
splitted = data.decode().split(seperator.decode())
content_type = splitted[0]
Bytes_ = splitted[1].encode()
salt = splitted[2]
return {"content_type": content_type, "bytes": Bytes_}
print("NEW CLIENT AT IP: " + str(addr[0]))
print("EXTANGING KEY")
send_raw("KEY", key)
client_key = recv_raw(1024)["bytes"]
if key == client_key:
print("KEY EXTANGE VERIFIED")
else:
print("UNABLE TO VERIFY, CLIENT MAY EXPERIENCE ISSUES")
print(key)
print(client_key)
encryption = True
print("GRAPPING SYSTEM INFO...")
sys_info_request = recv_raw(1024)
print("RECIVED, DECODING...")
sys_info = json.loads(sys_info_request["bytes"].decode())
print("BASIC INFO:")
print("Platoform: " + sys_info["platform"])
print("Architecture: " + str(sys_info["architecture"]))
print("Username: " + sys_info["username"])
if os.path.exists("autorun.txt"):
with open("autorun.txt", "r") as f:
print("FOUND AUTORUN, EXECUTING COMMANDS")
for line in f.readlines():
print("> " + line)
send_raw("command", line.encode())
output = recv_raw(1024)
print(output["bytes"].decode())
current_dir = sys_info["current_dir"]
while True:
try:
cmd = input(current_dir + "> " + sys_info["username"] + " $ ")
if cmd == "abort":
send_raw("abort", "".encode())
conn.close()
print("SAFE")
break
if cmd == "send_file":
# CODE GOES HERE
send_raw("command", cmd.encode())
output = recv_raw(1024)["bytes"].decode()
print(output)
except:
print("UNEXCPECTED ERROR")
while True:
conn, addr = s.accept()
threading.Thread(target=handle_client, args=(conn,addr,)).start()
我还没有在网上找到任何可以在我的senario中使用的东西。
I am trying to send an encrypted file over TCP sockets in python, I don't want to have to encrypt the message, save it in %TEMP% and then send it (it could fill up hard drive space).
I am following this code I found online at: https://gist.github.com/giefko/2fa22e01ff98e72a5be2
Here is my server code:
from random import choice
import socket, os, threading, json
from cryptography.fernet import Fernet
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPWRSTUVWXYZ1234567890!@#$%^&*()"
#read the key or generate
key = b""
if os.path.exists("client.key"):
with open("client.key", "rb") as f:
key = f.read()
else:
with open("client.key", "wb") as f:
key = Fernet.generate_key()
f.write(key)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 34467
host = "0.0.0.0"
s.bind((host, port))
print(f"LISTENING ON {host}:{port}")
s.listen(100)
def new_salt():
salt = ""
for x in range(15):
salt += choice(chars)
return salt
def handle_client(conn, addr):
encryption = False
def send_raw(content_type, Bytes_, salt=new_salt()):
seperator = "<|SEPERATE|>"
to_send = content_type + seperator + Bytes_.decode() + seperator + salt
to_send = to_send.encode()
if encryption:
to_send = Fernet(key).encrypt(to_send)
conn.send(to_send)
def recv_raw(BufferSize):
seperator = "<|SEPERATE|>".encode()
data = b""
while True:
data = conn.recv(BufferSize)
if data: break
if encryption:
data = Fernet(key).decrypt(data)
splitted = data.decode().split(seperator.decode())
content_type = splitted[0]
Bytes_ = splitted[1].encode()
salt = splitted[2]
return {"content_type": content_type, "bytes": Bytes_}
print("NEW CLIENT AT IP: " + str(addr[0]))
print("EXTANGING KEY")
send_raw("KEY", key)
client_key = recv_raw(1024)["bytes"]
if key == client_key:
print("KEY EXTANGE VERIFIED")
else:
print("UNABLE TO VERIFY, CLIENT MAY EXPERIENCE ISSUES")
print(key)
print(client_key)
encryption = True
print("GRAPPING SYSTEM INFO...")
sys_info_request = recv_raw(1024)
print("RECIVED, DECODING...")
sys_info = json.loads(sys_info_request["bytes"].decode())
print("BASIC INFO:")
print("Platoform: " + sys_info["platform"])
print("Architecture: " + str(sys_info["architecture"]))
print("Username: " + sys_info["username"])
if os.path.exists("autorun.txt"):
with open("autorun.txt", "r") as f:
print("FOUND AUTORUN, EXECUTING COMMANDS")
for line in f.readlines():
print("> " + line)
send_raw("command", line.encode())
output = recv_raw(1024)
print(output["bytes"].decode())
current_dir = sys_info["current_dir"]
while True:
try:
cmd = input(current_dir + "> " + sys_info["username"] + " $ ")
if cmd == "abort":
send_raw("abort", "".encode())
conn.close()
print("SAFE")
break
if cmd == "send_file":
# CODE GOES HERE
send_raw("command", cmd.encode())
output = recv_raw(1024)["bytes"].decode()
print(output)
except:
print("UNEXCPECTED ERROR")
while True:
conn, addr = s.accept()
threading.Thread(target=handle_client, args=(conn,addr,)).start()
I haven't found anything online that will work in my senario.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,所以您想打开文件,对其进行加密并将其发送并避免将临时文件写入硬盘,对吗?这起作用(取自您链接的示例服务器代码):
因此,我只是打开文件,读取1024字节,将其加密,然后将其发送。
Okay, so you want to open a file, encrypt it and send it and avoid writing a tempfile to the hard disc, right? This works (taken from the example server code you linked):
So, I am just opening the file, reading it 1024 bytes a time, encrypting it and then sending it along .. Does that answer your question?