https双向认证Socket版本---实践篇

Python-Https-Client-Socket版本.py

import socket
import ssl
class client_ssl:
    def send_hello(self, ):
        CA_FILE = "E:/python-TLS/TLStest证书/CA/ca.pem"
        KEY_FILE = "E:/python-TLS/TLStest证书/client/client.key"
        CERT_FILE = "E:/python-TLS/TLStest证书/client/client.cer"

        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()
Python-Https-Server-Socket版本.py

```python
import socket
import ssl

class server_ssl:
    def build_listen(self):
        CA_FILE = "E:/python-TLS/TLStest证书/CA/ca.pem"
        KEY_FILE = "E:/python-TLS/TLStest证书/server/server.key"
        CERT_FILE = "E:/python-TLS/TLStest证书/server/server.cer"
        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()

https双向认证Socket版本---实践篇_第1张图片
https双向认证Socket版本---实践篇_第2张图片
https双向认证Socket版本---实践篇_第3张图片

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