1

I'm trying to learn Network programming with Python language. In order that, I created a simple chat program with python. Now I want to encrypt communication between Server and Clients. How can I do that? The following code is my server code:

        TcpSocket.bind(("0.0.0.0",8000))
        TcpSocket.listen(2)
        print("I'm waiting for a connection...!")
        (client, (ip, port)) = TcpSocket.accept()
        print("Connection recived from the {}".format(ip))
        messageToClient = "You connected to the server sucessfuly.\n"
        client.send(messageToClient.encode('ascii'))

        dataRecived = "Message!"

        while True:
                dataRecived = client.recv(1024)
                print("Client :", dataRecived)
                print("Server :")
                dataSend = raw_input()
                client.send(str(dataSend) + "\n")


        print("Connection has been closed.")
        client.close()
        print("Server has been shutdowned.")
        TcpSocket.close()



def main():

        try:
                print("Server has started.")
                connectionOrianted()

        except :
                print("Maybe connection terminated.")
        finally:
                print("Session has closed.")



if __name__ == "__main__": main()

And the following code is my client code.

#!/usr/bin/python3

import socket
import sys
from builtins import input

def main():

    try:
        serverHostNumber = input("Please enter the ip address of the server: \n")
        serverPortNumber = input("Please enter the port of the server: \n")

        # create a socket object
        TcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
        # connection to hostname on the port.
        TcpSocket.connect((serverHostNumber, int(serverPortNumber)))                                                                    

        while True:
            data = TcpSocket.recv(1024)
            print("Server : ", data)
            sendData = input("Client : ")

            if sendData == "exit":
                    TcpSocket.close()
                    sys.exit()

            TcpSocket.send(sendData.encode(encoding='ascii', errors='strict'))

    except Exception as e:
        print("The error: ", e) 
        TcpSocket.close()
        sys.exit()      

if __name__ == "__main__" : main()
wogsland
  • 9,106
  • 19
  • 57
  • 93

1 Answers1

0

I'm assuming you want to use the defacto standard for network encryption SSL (Secure Sockets Layer).

Client side is easy, basically you wrap your standard socket with an SSL socket, client side is built in so there's nothing special to install or import.

#!/usr/bin/python3

import socket
import sys
from builtins import input

def main():

    try:
        serverHostNumber = input("Please enter the ip address of the server: \n")
        serverPortNumber = input("Please enter the port of the server: \n")

        # create a socket object
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # connection to hostname on the port.
        sock.connect((serverHostNumber, int(serverPortNumber)))
        TcpSocket = socket.ssl(sock)



        while True:
            data = TcpSocket.recv(1024)
            print("Server : ", data)
            sendData = input("Client : ")

            if sendData == "exit":
                    TcpSocket.close()
                    sys.exit()

            TcpSocket.send(sendData.encode(encoding='ascii', errors='strict'))

    except Exception as e:
        print("The error: ", e) 
        sys.exit()      

if __name__ == "__main__" : main()

Server side is more difficult.

First you will need to install pyopenssl

After that you will need to generate a private key and a certificate (unless you already have one), this is pretty straight forward on linux, just run this from the command line:

openssl genrsa 1024 > key
openssl req -new -x509 -nodes -sha1 -days 365 -key key > cert

For Windows you will need to use one of these methods

Finally, once all the prerequisites are done SSl wraps sockets for the server side much like it does for the client side.

import socket
from OpenSSL import SSL

context = SSL.Context(SSL.SSLv23_METHOD)
context.use_privatekey_file('key')
context.use_certificate_file('cert')

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = SSL.Connection(context, s)
s.bind(("0.0.0.0",8000))
        s.listen(2)
        print("I'm waiting for a connection...!")
        (client, (ip, port)) = s.accept()
        print("Connection recived from the {}".format(ip))
        messageToClient = "You connected to the server sucessfuly.\n"
        client.send(messageToClient.encode('ascii'))

        dataRecived = "Message!"

        while True:
                dataRecived = client.recv(1024)
                print("Client :", dataRecived)
                print("Server :")
                dataSend = raw_input()
                client.send(str(dataSend) + "\n")


        print("Connection has been closed.")
        client.close()
        print("Server has been shutdowned.")
        s.close()



def main():

        try:
                print("Server has started.")
                connectionOrianted()

        except :
                print("Maybe connection terminated.")
        finally:
                print("Session has closed.")

I haven't had the chance to test these scripts, but they should work. I hope this answers your question.

Community
  • 1
  • 1
Noah Wood
  • 40
  • 5
  • 1
    I fixed the problem of the server, but the client code shows the following error : TcpSocket.close() UnboundLocalError: local variable 'TcpSocket' referenced before assignment – Milad Kahsari Alhadi Sep 20 '15 at 21:45
  • 1
    Hmm... It seems the script is trying to close the connection if the connection fails, but the variable isn't defined before it happens. If you define the variable before it will work, or you can just remove the TcpSocket.close() as I have done in the code. – Noah Wood Sep 21 '15 at 02:19