简体   繁体   English

编码通讯

[英]Encoded Communication

I'm trying to learn Network programming with Python language. 我正在尝试学习使用Python语言的网络编程。 In order that, I created a simple chat program with python. 为此,我使用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()

I'm assuming you want to use the defacto standard for network encryption SSL (Secure Sockets Layer). 我假设您想对网络加密SSL(安全套接字层)使用事实上的标准。

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. 客户端很容易,基本上是用SSL套接字包装标准套接字,客户端是内置的,因此没有什么特别的安装或导入。

#!/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 首先,您需要安装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: 之后,您将需要生成一个私钥和一个证书(除非您已经拥有一个),这在Linux上非常简单,只需从命令行运行即可:

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 对于Windows,您将需要使用以下方法之一

Finally, once all the prerequisites are done SSl wraps sockets for the server side much like it does for the client side. 最后,一旦完成所有先决条件,SS1就会像为客户端那样包装服务器端的套接字。

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. 我希望这回答了你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM