Secure socket programming in Python

Public key will be sent to client and private will be used by server only.This is how we generate RSA key:random = Random.new().read RSAkey = RSA.generate(1024, random) public = RSAkey.publickey().exportKey() private = RSAkey.exportKey()After generating the keys, we need to hash the public key and a session key to send to every client for MAC validation..We can also store those keys in text file for further usage.(Not recommended. Better to use a new key for every new session).To bind the socket with the IP and Port, we don’t have to do a lot of coding..I still remember those days when I used to do socket programming in C++..If you are doing socket programming in C++, you will have better control comparing to Python but still, we need fast development that’s why I moved to Python.Okay, enough of talking..Let’s get back to coding again.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind((host, port)) server.listen(1)The code above is enough to establish a socket connection.We will assign a thread for listening to incoming connections..Creating a thread in Python is very easy.threading_accept = threading.Thread(target=ConnectionSetup) threading_accept.start()ConnectionSetupis our function where we are listening to incoming connections..We have 2 more functions for adding padding to the key(user’s password)..User’s password will be used as a key for encrypting and decrypting the messages..In our ConnectionSetupfunction, we will do some validations..First, client will send a concat string of public key generated by client and hash of the public key..By this way, we can prevent Man-in-the-middle attack..Because, the logic of passing public key is knows only by server and client.. More details

Leave a Reply