编码通信

Encoded Communication

我正在尝试使用 Python 语言学习网络编程。为此,我用 python 创建了一个简单的聊天程序。现在我想加密服务器和客户端之间的通信。我怎样才能做到这一点?以下代码是我的服务器代码:

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

下面的代码是我的客户端代码。

#!/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()

我假设您想使用网络加密 SSL(安全套接字层)的事实标准。

客户端很简单,基本上你用 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()

服务器端比较难。

首先你需要安装pyopenssl

之后您将需要生成私钥和证书(除非您已经拥有),这在 linux 上非常简单,只需 运行 从命令行执行此操作:

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

对于Windows,您需要use one of these methods

最后,一旦完成所有先决条件,SSl 就会像为客户端一样为服务器端包装套接字。

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.")

我还没有机会测试这些脚本,但它们应该可以工作。我希望这能回答你的问题。