1 min read

Python SSL Module

The ssl module provides access to Transport Layer Security (often known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets, both client-side and server-side. This module uses the OpenSSL library.

Importing the Module

import ssl

SSL Context

The SSLContext object holds various data that is long-lived across connections, such as SSL configuration options, certificates, and private keys.

Creating a Default Context

The recommended way to get a context is ssl.create_default_context(). It returns a context with secure default settings.

import ssl

context = ssl.create_default_context()

Client-Side Usage

To secure a client connection, you wrap an existing socket.

import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
        # ... send and receive data ...

Server-Side Usage

For a server, you need to load a certificate and private key.

import socket
import ssl

context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="server.crt", keyfile="server.key")

bindsocket = socket.socket()
bindsocket.bind(('0.0.0.0', 10023))
bindsocket.listen(5)

while True:
    newsocket, fromaddr = bindsocket.accept()
    conn = context.wrap_socket(newsocket, server_side=True)
    # ... handle connection ...

programming/python/python