Sending encrypted strings using a socket in Python

I made a simple server program that can receive data from 4 different clients at a time. Now I want to send some data using AES-128 Encryption, but that needs to be decrypted on the server side. Here is my code for the 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()

      

How can I change client code and server code to include AES-128 encryption .. Please help me in this regard.

+3


source to share


1 answer


Use Python Crypto module which supports AES. You need a symmetric key (the same key used for encryption and decryption). The same key can be generated both on the server and on the client, if the same passphrase and initialization vector (IV) are used.

Summary: 1. The same key that will be used for encryption and decryption 2. Use Crypto.Cipher.AES

AES has methods for generating keys, encrypting and decrypting data. The following links are with actual code. pycrypto fooobar.com/questions/55567 / ...

Customer. Call this method to encrypt your data and send 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. Get the 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

      

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

+7


source







All Articles