python 搞TCP TLS1.3加密最直观的版本---SOCKET版

Client端代码

import socket
import ssl


class client_ssl:
    def send_hello(self, ):
        CA_FILE = "E:/python-TLS/证书及秘钥/cacert.pem"
        KEY_FILE = "E:/python-TLS/证书及秘钥/client-key.pem"
        CERT_FILE = "E:/python-TLS/证书及秘钥/client-cert.pem"

        context = ssl.SSLContext(ssl.PROTOCOL_TLS)
        context.check_hostname = False
        context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
        context.load_verify_locations(CA_FILE)
        context.verify_mode = ssl.CERT_REQUIRED

        # 与服务端建立socket连接
        with socket.socket() as sock:
            # 将socket打包成SSL socket
            with context.wrap_socket(sock, server_side=False) as ssock:
                ssock.connect(('127.0.0.1', 5678))
                # 向服务端发送信息
                msg = "do i connect with server ?".encode("utf-8")
                ssock.send(msg)
                # 接收服务端返回的信息
                msg = ssock.recv(1024).decode("utf-8")
                print(f"receive msg from server : {msg}")
                ssock.close()


if __name__ == "__main__":
    client = client_ssl()
    client.send_hello()

Server端代码

import socket
import ssl

class server_ssl:
    def build_listen(self):
        CA_FILE = "E:/python-TLS/证书及秘钥/cacert.pem"
        KEY_FILE = "E:/python-TLS/证书及秘钥/serverkey.pem"
        CERT_FILE = "E:/python-TLS/证书及秘钥/servercert.pem"
        context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
        context.load_verify_locations(CA_FILE)
        context.verify_mode = ssl.CERT_REQUIRED

        # 监听端口
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
            # 将socket打包成SSL socket
            with context.wrap_socket(sock, server_side=True) as ssock:
                ssock.bind(('127.0.0.1', 5678))
                ssock.listen(5)
                while True:
                    # 接收客户端连接
                    client_socket, addr = ssock.accept()
                    # 接收客户端信息
                    msg = client_socket.recv(1024).decode("utf-8")
                    print(f"receive msg from client {addr}{msg}")
                    # 向客户端发送信息
                    msg = f"yes , you have client_socketect with server.\r\n".encode("utf-8")
                    client_socket.send(msg)
                    client_socket.close()


if __name__ == "__main__":
    server = server_ssl()
    server.build_listen()

python 搞TCP TLS1.3加密最直观的版本---SOCKET版_第1张图片
python 搞TCP TLS1.3加密最直观的版本---SOCKET版_第2张图片

参见文档:https://blog.csdn.net/vip97yigang/article/details/84721027?utm_medium=toutiao_ios&spm=1001.2101.3001.4242.1&utm_relevant_index=3&share_token=3A5DB6F4-9011-4019-9622-71988DEBA688&tt_from=weixin&utm_source=weixin&utm_campaign=client_share&wxshare_count=1

你可能感兴趣的:(笔记,python,网络安全,safari)