python - 在 Python 中使用套接字发送加密字符串

标签 python sockets encryption

我制作了一个简单的服务器程序,可以一次从 4 个不同的客户端接收数据。现在我想用 AES-128 加密发送一些数据,但应该在服务器端解码。 这是我的服务器代码:

from socket import *
from threading import Thread

def clientHandler():
    conn, addr = s.accept()
    print addr, "is connected"
    while 1:
        data = conn.recv(1024)
        if not data:
            break
        print "Received Message", repr(data)


HOST = "" #localhost
PORT = 15000


s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(4)

print "Server is runnig"
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()

for i in range(4):
    Thread(target=clientHandler).start()

s.close()

我正在从我的客户端发送这样的数据

from socket import *
s = socket()
s.connect(("localhost",15000))
s.send()

我应该如何修改我的客户端代码和服务器代码以在其中包含 AES-128 加密。请在这方面帮助我。

最佳答案

使用支持 AES 的 Python 加密模块。您需要一个对称 key (用于加密和解密的相同 key )。如果使用相同的密码短语和初始化向量(IV),则可以在服务器和客户端中生成相同的 key 。

总结: 1.加密和解密使用相同的 key 2.使用Crypto.Cipher.AES

AES 具有生成 key 、加密和解密数据的方法。以下链接具有实际代码。 pycrypto stackoverflow

客户端 - 调用此方法加密您的数据并发送加密数据

from Crypto.Cipher import AES

def do_encrypt(message):
    obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
    ciphertext = obj.encrypt(message)
    return ciphertext

Server - 接收数据并调用此方法解密数据

from Crypto.Cipher import AES

def do_decrypt(ciphertext):
    obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
    message = obj2.decrypt(ciphertext)
    return message

这是一个示例代码,请确保您选择了一个强密码和 IV。

关于python - 在 Python 中使用套接字发送加密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27287306/

相关文章:

python - Matplotlib-动画 "No MovieWriters Available"

Python - 如何并行使用和操作目录中的文件

python - Python 扩展切片表示法的正式语法?

networking - 如何判断套接字从哪个接口(interface)接收到消息?

python - 突出显示一堆单词?

c# - 结束连接异常

c - 使用 recv 接收传入的 char 数组

C# 如果我有私钥我该如何解密?

actionscript-3 - As3 加密库

c# - 输入不是有效的 Base64 字符串,因为它在 C# 中包含非 base 64 字符?