使用Python中的套接字发送加密的字符串 [英] Sending Encrypted strings using socket in Python

查看:56
本文介绍了使用Python中的套接字发送加密的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I made a simple server program that is able to receive data from 4 different clients at a time. Now I want to send some data with AES-128 Encryption but that should be decoded at the server side. Here is my code for server:

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()

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

And I am sending data like this from my client side

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

我应该如何修改我的客户端代码和服务器代码,使其内部包含AES-128加密..请在这方面为我提供帮助.

How should I modify my client code and server code to include AES-128 Encryption inside of it .. Kindly help me in this regard.

推荐答案

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

Use Python's Crypto module which supports AES. You need a symmetric key (same key used to encrypt and decrypt). The same key can be generated in both server and client if the same passphrase and the initialization vector(IV) are used.

摘要:1.用于加密和解密的相同密钥2.使用Crypto.Cipher.AES

Summary: 1. Same key to be used to encrypt and decrypt 2. Use Crypto.Cipher.AES

AES具有生成密钥,加密和解密数据的方法.以下链接具有实际代码. pycrypto

AES has methods to generate key, encrypt and decrypt data. Following links have the actual code. pycrypto stackoverflow

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

Client - Call this method to encrypt your data and send the encrypted data

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 - Receive data and call this method to decrypt the data

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.

This is a sample code, make sure you choose a strong passphrase and IV.

这篇关于使用Python中的套接字发送加密的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆