ZetCode

Python SSL/TLS certificates

last modified October 30, 2026 Python 3.15

In this article we show how to work with SSL/TLS certificates in Python. We inspect and verify certificates of remote servers, create a private key and a certificate signing request, set up a local certificate authority for development, and use the certificates in an HTTPS server and client.

SSL and TLS

SSL (Secure Sockets Layer) and its successor TLS (Transport Layer Security) are cryptographic protocols that protect data sent over a network. They encrypt the traffic, protect it from tampering, and let the client verify the identity of the server. All SSL versions and TLS 1.0 and 1.1 are deprecated; current software uses TLS 1.2 and TLS 1.3. The name SSL survives in everyday language and in the name of Python's ssl module.

A TLS certificate is an X.509 document that binds a public key to an identity, usually a domain name. It contains the subject (who the certificate belongs to), the issuer (who signed it), a validity period, the public key, and extensions such as the list of domain names in the Subject Alternative Name (SAN) extension. The matching private key never leaves the server.

Certificates are signed by a certificate authority (CA). A server certificate is usually signed by an intermediate CA, which is in turn signed by a root CA. The root certificates are preinstalled in the operating system or the browser. A client trusts a server certificate if it can build a chain of valid signatures from the certificate up to one of the trusted roots, and if the name it connected to appears in the certificate.

Certificate types

Certificates differ in how thoroughly the CA checks the applicant and in how many names they cover.

The wildcard and multi-domain variants are combined with DV, OV, or EV validation. A certificate can be both a wildcard and a multi-domain one; the certificate of example.com shown later covers example.com and *.example.com.

Obtaining a certificate

To get a certificate from a public CA, we generate a private key and a Certificate Signing Request (CSR). The CSR contains the public key and the requested names and is signed with the private key. We send only the CSR to the CA; the private key stays on our server. The CA validates our control of the domain (and the organization details for OV and EV), and returns the signed certificate together with the intermediate certificates.

Let's Encrypt issues free DV certificates through the automated ACME protocol. ACME clients such as Certbot create the key and the CSR, prove the domain control, and renew the certificates before they expire. OV and EV certificates come from commercial CAs and their resellers. For development and internal services, we can run our own CA, as shown later in this article.

The ssl module

The ssl module from the standard library wraps sockets in TLS. It verifies certificates against the system's trusted roots, checks host names, and gives access to the certificate of the other side. It cannot create certificates; for that, we use the OpenSSL command line tool or the third-party cryptography library.

The ssl.create_default_context function creates an SSLContext with secure defaults: certificate verification and host name checking are on and TLS 1.2 is the minimum version. We should use it instead of building a context by hand. Some examples need the cryptography package.

$ pip install cryptography

Inspecting a server certificate

The getpeercert method returns the certificate of the other side of a verified connection as a dictionary.

peer_cert.py
import socket
import ssl

hostname = 'example.com'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        cert = ssock.getpeercert()

subject = dict(item[0] for item in cert['subject'])
issuer = dict(item[0] for item in cert['issuer'])

print('Subject:', subject['commonName'])
print('Issuer:', issuer['organizationName'], '/', issuer['commonName'])
print('Valid from:', cert['notBefore'])
print('Valid until:', cert['notAfter'])
print('Serial number:', cert['serialNumber'])
print('Alternative names:')

for kind, value in cert['subjectAltName']:
    print(f'  {kind}: {value}')

We open a TCP connection to port 443 and wrap it in TLS with wrap_socket. The server_hostname parameter is required: it is sent to the server in the SNI extension, so that the server picks the right certificate, and it is the name the certificate is checked against. The handshake runs when the socket is wrapped; if the certificate is not valid, wrap_socket raises an exception.

The subject and the issuer are stored as tuples of relative distinguished names; we turn them into dictionaries. The subjectAltName item lists the names the certificate is valid for.

$ python peer_cert.py
Subject: example.com
Issuer: SSL Corporation / Cloudflare TLS Issuing ECC CA 3
Valid from: Sep 26 22:49:11 2026 GMT
Valid until: Dec 25 22:56:35 2026 GMT
Serial number: 01EEE6AABB521D5E14FC315FD9985690
Alternative names:
  DNS: example.com
  DNS: *.example.com

Downloading a certificate

The ssl.get_server_certificate function returns the certificate of a server in the PEM format.

server_cert.py
import hashlib
import ssl
from pathlib import Path

pem = ssl.get_server_certificate(('example.com', 443))
der = ssl.PEM_cert_to_DER_cert(pem)

Path('example.com.pem').write_text(pem)

lines = pem.splitlines()
print(lines[0])
print(lines[1])
print('...')
print(lines[-1])

digest = hashlib.sha256(der).hexdigest().upper()
fingerprint = ':'.join(digest[i:i + 2] for i in range(0, len(digest), 2))

print(f'DER size: {len(der)} bytes')
print(f'SHA256 fingerprint: {fingerprint}')

PEM is the Base64 text encoding of the binary DER format, wrapped in BEGIN and END lines. The .pem, .crt, and .cer extensions are only conventions; the content decides the format. We save the certificate to a file, convert it to DER with PEM_cert_to_DER_cert, and compute the SHA-256 fingerprint of the DER bytes. The fingerprint identifies the certificate uniquely; it is used, for instance, to pin a certificate.

The openssl x509 command computes the same fingerprint from the saved file.

$ python server_cert.py
-----BEGIN CERTIFICATE-----
MIID5jCCA42gAwIBAgIQAe7mqrtSHV4U/DFf2ZhWkDAKBggqhkjOPQQDAjBRMQsw
...
-----END CERTIFICATE-----
DER size: 1002 bytes
SHA256 fingerprint: 85:CA:6A:B0:68:E9:BC:CE:88:B6:C4:AA:3C:47:F7:D1:72:28:13:4A:45:7F:87:0D:38:00:E6:22:3A:0D:F0:7A
$ openssl x509 -in example.com.pem -noout -fingerprint -sha256
sha256 Fingerprint=85:CA:6A:B0:68:E9:BC:CE:88:B6:C4:AA:3C:47:F7:D1:72:28:13:4A:45:7F:87:0D:38:00:E6:22:3A:0D:F0:7A

Checking certificate expiry

Certificates are valid only for a limited time. Since March 2026, public TLS certificates are valid for at most 200 days, and the limit keeps shrinking in the coming years. Monitoring the expiry dates is therefore a common task.

cert_expiry.py
import socket
import ssl
import time

hosts = ['example.com', 'python.org', 'github.com', 'letsencrypt.org']
context = ssl.create_default_context()

for host in hosts:
    with socket.create_connection((host, 443), timeout=10) as sock:
        with context.wrap_socket(sock, server_hostname=host) as ssock:
            cert = ssock.getpeercert()

    expires = ssl.cert_time_to_seconds(cert['notAfter'])
    days = int((expires - time.time()) // 86400)

    print(f'{host:16} {cert["notAfter"]:26} {days:4} days left')

The notAfter item holds the expiry date as a string. The ssl.cert_time_to_seconds function converts it to seconds since the epoch, which we compare with the current time.

$ python cert_expiry.py
example.com      Dec 25 22:56:35 2026 GMT     56 days left
python.org       Feb 14 13:03:45 2027 GMT    106 days left
github.com       Jan 27 23:59:59 2027 GMT     89 days left
letsencrypt.org  Dec  3 14:34:31 2026 GMT     33 days left

The certificate chain

The get_unverified_chain and get_verified_chain methods, added in Python 3.13, return the certificate chain as a list of DER-encoded certificates.

cert_chain.py
import socket
import ssl

from cryptography import x509

hostname = '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:
        sent = ssock.get_unverified_chain()
        chain = ssock.get_verified_chain()

print(f'The server sent {len(sent)} certificates')
print(f'The verified chain has {len(chain)} certificates')
print()

for depth, der in enumerate(chain):
    cert = x509.load_der_x509_certificate(der)
    print(f'{depth}: {cert.subject.rfc4514_string()}')
    print(f'   issued by {cert.issuer.rfc4514_string()}')

The unverified chain contains the certificates the server sent. The verified chain is the one OpenSSL built from the server certificate to a trusted root. The ssl module does not parse DER certificates, so we load them with the x509.load_der_x509_certificate function of the cryptography library.

The python.org server sends its certificate and the intermediate CA certificate. The root certificate comes from the local trust store; the root is self-signed, its subject and issuer are the same.

$ python cert_chain.py
The server sent 2 certificates
The verified chain has 3 certificates

0: CN=www.python.org
   issued by CN=GlobalSign Atlas R3 DV TLS CA 2025 Q4,O=GlobalSign nv-sa,C=BE
1: CN=GlobalSign Atlas R3 DV TLS CA 2025 Q4,O=GlobalSign nv-sa,C=BE
   issued by CN=GlobalSign,O=GlobalSign,OU=GlobalSign Root CA - R3
2: CN=GlobalSign,O=GlobalSign,OU=GlobalSign Root CA - R3
   issued by CN=GlobalSign,O=GlobalSign,OU=GlobalSign Root CA - R3

Connection parameters

Python 3.15 adds methods that show how a connection was secured. The group method returns the key exchange group and the server_sigalg method returns the signature algorithm the server used in the handshake. The SSLContext.get_groups and set_groups methods list and restrict the groups offered by the context.

tls_info.py
import socket
import ssl

hostname = 'example.com'


def connect(context):

    with socket.create_connection((hostname, 443)) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as ssock:
            print('Protocol:', ssock.version())
            print('Cipher:', ssock.cipher()[0])
            print('Key exchange group:', ssock.group())
            print('Server signature:', ssock.server_sigalg())


context = ssl.create_default_context()
hybrid = [g for g in context.get_groups() if 'MLKEM' in g]
print('ML-KEM groups:', ', '.join(hybrid))
print()

connect(context)
print()

context = ssl.create_default_context()
context.set_groups('x25519:secp256r1')
connect(context)

The example connects twice. With the default settings, Python 3.15 built against OpenSSL 3.5 negotiates X25519MLKEM768, a hybrid of the classic X25519 key exchange and the post-quantum ML-KEM algorithm. Such a key exchange protects the recorded traffic even against future quantum computers. In the second connection, we offer only classic groups with set_groups, so the server falls back to x25519.

The version and cipher methods return the protocol version and the cipher suite. The available groups depend on the OpenSSL version Python is linked with.

$ python tls_info.py
ML-KEM groups: MLKEM512, MLKEM768, MLKEM1024, SecP256r1MLKEM768, X25519MLKEM768, SecP384r1MLKEM1024

Protocol: TLSv1.3
Cipher: TLS_AES_256_GCM_SHA384
Key exchange group: X25519MLKEM768
Server signature: ecdsa_secp256r1_sha256

Protocol: TLSv1.3
Cipher: TLS_AES_256_GCM_SHA384
Key exchange group: x25519
Server signature: ecdsa_secp256r1_sha256

Verification errors

If a certificate cannot be verified, the handshake fails with ssl.SSLCertVerificationError. The badssl.com site provides hosts with intentionally broken certificates.

verify_errors.py
import socket
import ssl

hosts = ['badssl.com', 'expired.badssl.com', 'wrong.host.badssl.com',
         'self-signed.badssl.com', 'untrusted-root.badssl.com']

context = ssl.create_default_context()

for host in hosts:

    try:
        with socket.create_connection((host, 443), timeout=10) as sock:
            with context.wrap_socket(sock, server_hostname=host):
                print(f'{host}: OK')
    except ssl.SSLCertVerificationError as e:
        print(f'{host}: {e.verify_message} (code {e.verify_code})')

The verify_message and verify_code attributes of the exception tell why the verification failed. The certificate of expired.badssl.com has expired, the certificate of wrong.host.badssl.com is issued for a different name, and the last two certificates are not signed by a trusted CA.

We should never fix such errors by turning verification off with check_hostname = False and CERT_NONE. Without verification, an attacker can impersonate the server and read the traffic. Instead, we fix the certificate on the server or tell the client which CA to trust.

$ python verify_errors.py
badssl.com: OK
expired.badssl.com: certificate has expired (code 10)
wrong.host.badssl.com: Hostname mismatch, certificate is not valid for 'wrong.host.badssl.com'. (code 62)
self-signed.badssl.com: self-signed certificate (code 18)
untrusted-root.badssl.com: self-signed certificate in certificate chain (code 19)

Creating a CSR with OpenSSL

The openssl req command generates a private key and a CSR in one step.

The command creates an elliptic curve key on the P-256 curve; a rsa:2048 key works as well. The -nodes option leaves the key unencrypted, so a server can load it without a password. The -subj option sets the subject and -addext adds the Subject Alternative Name extension; browsers check only the SAN names, not the common name. The private key file is readable only by its owner. The -verify option checks the signature of the CSR.

The example.com.csr file is what we submit to the CA. The example.com.key file must stay secret; if it leaks, the certificate must be revoked.

$ openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -keyout example.com.key -out example.com.csr -subj "/C=SK/O=Example/CN=example.com" -addext "subjectAltName=DNS:example.com,DNS:www.example.com"
$ chmod 600 example.com.key
$ ls -l example.com.key example.com.csr
-rw-rw-r-- 1 user user 481 Oct 30 22:26 example.com.csr
-rw------- 1 user user 241 Oct 30 22:26 example.com.key
$ openssl req -in example.com.csr -noout -verify -subject
Certificate request self-signature verify OK
subject=C = SK, O = Example, CN = example.com

Creating a CSR with cryptography

The same key and CSR can be created in Python with the cryptography library.

create_csr.py
from pathlib import Path

from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID

key = ec.generate_private_key(ec.SECP256R1())

name = x509.Name([
    x509.NameAttribute(NameOID.COUNTRY_NAME, 'SK'),
    x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Example'),
    x509.NameAttribute(NameOID.COMMON_NAME, 'example.com'),
])

alt_names = x509.SubjectAlternativeName([
    x509.DNSName('example.com'),
    x509.DNSName('www.example.com'),
])

csr = (x509.CertificateSigningRequestBuilder()
       .subject_name(name)
       .add_extension(alt_names, critical=False)
       .sign(key, hashes.SHA256()))

key_file = Path('example.com.key')
key_file.unlink(missing_ok=True)
key_file.touch(mode=0o600)
key_file.write_bytes(key.private_bytes(
    serialization.Encoding.PEM,
    serialization.PrivateFormat.PKCS8,
    serialization.NoEncryption(),
))

Path('example.com.csr').write_bytes(csr.public_bytes(serialization.Encoding.PEM))

san = csr.extensions.get_extension_for_class(x509.SubjectAlternativeName)

print('Subject:', csr.subject.rfc4514_string())
print('Names:', san.value.get_values_for_type(x509.DNSName))
print('Signature valid:', csr.is_signature_valid)

We generate a P-256 key with ec.generate_private_key and build the request with CertificateSigningRequestBuilder. The request is signed with the private key, which proves to the CA that we own the key.

The key is serialized to PKCS #8 PEM. Before writing it, we create the file with the 0o600 mode, so that the key is never readable by other users. The script replaces the files created by OpenSSL in the previous section.

$ python create_csr.py
Subject: CN=example.com,O=Example,C=SK
Names: ['example.com', 'www.example.com']
Signature valid: True

A local certificate authority

For development and internal services, we can create our own CA and issue certificates that work like the public ones. The clients only need to trust the CA certificate. Tools such as mkcert do the same; here we build the CA with the cryptography library.

create_ca.py
import datetime
from pathlib import Path

from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID

key = ec.generate_private_key(ec.SECP384R1())
name = x509.Name([
    x509.NameAttribute(NameOID.COMMON_NAME, 'Local Development CA'),
])
now = datetime.datetime.now(datetime.UTC)

usage = x509.KeyUsage(
    digital_signature=False, content_commitment=False,
    key_encipherment=False, data_encipherment=False, key_agreement=False,
    key_cert_sign=True, crl_sign=True, encipher_only=False,
    decipher_only=False,
)

cert = (x509.CertificateBuilder()
        .subject_name(name)
        .issuer_name(name)
        .public_key(key.public_key())
        .serial_number(x509.random_serial_number())
        .not_valid_before(now)
        .not_valid_after(now + datetime.timedelta(days=3650))
        .add_extension(x509.BasicConstraints(ca=True, path_length=0),
                       critical=True)
        .add_extension(usage, critical=True)
        .add_extension(x509.SubjectKeyIdentifier.from_public_key(
            key.public_key()), critical=False)
        .sign(key, hashes.SHA384()))

key_file = Path('ca.key')
key_file.unlink(missing_ok=True)
key_file.touch(mode=0o600)
key_file.write_bytes(key.private_bytes(
    serialization.Encoding.PEM,
    serialization.PrivateFormat.PKCS8,
    serialization.NoEncryption(),
))

Path('ca.pem').write_bytes(cert.public_bytes(serialization.Encoding.PEM))

print('Subject:', cert.subject.rfc4514_string())
print('Issuer:', cert.issuer.rfc4514_string())
print('Valid until:', cert.not_valid_after_utc.date())

A CA certificate is self-signed: the subject and the issuer are the same name, and the certificate is signed with its own key. The BasicConstraints extension marks it as a CA; a path length of 0 means it can sign only end-entity certificates, not other CAs. The KeyUsage extension allows the key to sign certificates and revocation lists. The SubjectKeyIdentifier extension lets verifiers match the certificates the CA signs to its key.

$ python create_ca.py
Subject: CN=Local Development CA
Issuer: CN=Local Development CA
Valid until: 2036-10-27

Issuing certificates

The next script uses the CA to issue a server certificate for localhost and a client certificate for a user named alice.

issue_cert.py
import datetime
import ipaddress
from pathlib import Path

from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID

ca_key = serialization.load_pem_private_key(Path('ca.key').read_bytes(), None)
ca_cert = x509.load_pem_x509_certificate(Path('ca.pem').read_bytes())


def issue(common_name, alt_names, usage, filename):

    key = ec.generate_private_key(ec.SECP256R1())
    now = datetime.datetime.now(datetime.UTC)

    cert = (x509.CertificateBuilder()
            .subject_name(x509.Name([
                x509.NameAttribute(NameOID.COMMON_NAME, common_name),
            ]))
            .issuer_name(ca_cert.subject)
            .public_key(key.public_key())
            .serial_number(x509.random_serial_number())
            .not_valid_before(now)
            .not_valid_after(now + datetime.timedelta(days=90))
            .add_extension(x509.SubjectAlternativeName(alt_names),
                           critical=False)
            .add_extension(x509.BasicConstraints(ca=False, path_length=None),
                           critical=True)
            .add_extension(x509.ExtendedKeyUsage([usage]), critical=False)
            .add_extension(x509.SubjectKeyIdentifier.from_public_key(
                key.public_key()), critical=False)
            .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(
                ca_key.public_key()), critical=False)
            .sign(ca_key, hashes.SHA384()))

    key_file = Path(f'{filename}.key')
    key_file.unlink(missing_ok=True)
    key_file.touch(mode=0o600)
    key_file.write_bytes(key.private_bytes(
        serialization.Encoding.PEM,
        serialization.PrivateFormat.PKCS8,
        serialization.NoEncryption(),
    ))

    Path(f'{filename}.pem').write_bytes(
        cert.public_bytes(serialization.Encoding.PEM))

    print(f'{filename}.pem: {cert.subject.rfc4514_string()}, '
          f'valid until {cert.not_valid_after_utc.date()}')


issue('localhost',
      [x509.DNSName('localhost'),
       x509.IPAddress(ipaddress.ip_address('127.0.0.1'))],
      ExtendedKeyUsageOID.SERVER_AUTH, 'server')

issue('alice',
      [x509.RFC822Name('alice@example.com')],
      ExtendedKeyUsageOID.CLIENT_AUTH, 'client')

The certificates are signed with the CA key and carry the CA subject as the issuer. The server certificate lists localhost and 127.0.0.1 in the SAN extension, so that it is valid for both names. The ExtendedKeyUsage extension restricts each certificate to server or client authentication.

The AuthorityKeyIdentifier extension links each certificate to the CA key. Since Python 3.13, the default context sets the VERIFY_X509_STRICT flag, which rejects certificates without this extension. The certificates are valid for 90 days.

The openssl verify command confirms that both certificates chain up to our CA.

$ python issue_cert.py
server.pem: CN=localhost, valid until 2027-01-28
client.pem: CN=alice, valid until 2027-01-28
$ openssl verify -CAfile ca.pem server.pem client.pem
server.pem: OK
client.pem: OK
$ openssl x509 -in server.pem -noout -ext subjectAltName,extendedKeyUsage
X509v3 Subject Alternative Name: 
    DNS:localhost, IP Address:127.0.0.1
X509v3 Extended Key Usage: 
    TLS Web Server Authentication

An HTTPS server

A server needs its certificate and the private key. We load them into a server-side context and wrap the listening socket of an HTTP server.

https_server.py
import ssl
from http.server import BaseHTTPRequestHandler, HTTPServer


class Handler(BaseHTTPRequestHandler):

    def do_GET(self):

        body = f'Hello over {self.connection.version()}\n'.encode()

        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)


context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile='server.pem', keyfile='server.key')

httpd = HTTPServer(('127.0.0.1', 8443), Handler)
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)

print('Serving on https://localhost:8443/')
try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass

The Purpose.CLIENT_AUTH argument creates a context for the server side; the default Purpose.SERVER_AUTH is for clients. The load_cert_chain method loads the certificate and the key. With a certificate from a public CA, the certificate file must contain the server certificate followed by the intermediate certificates, such as the fullchain.pem file from Certbot.

Every accepted connection goes through the TLS handshake. The handler reports the negotiated protocol version. The server runs until we stop it with Ctrl+C.

https_client.py
import ssl
import urllib.error
import urllib.request

url = 'https://localhost:8443/'

context = ssl.create_default_context(cafile='ca.pem')

with urllib.request.urlopen(url, context=context) as resp:
    print(resp.status, resp.read().decode().strip())

try:
    urllib.request.urlopen(url)
except urllib.error.URLError as e:
    print('Without ca.pem:', e.reason.verify_message)

The client tells the context to trust our CA with the cafile parameter and passes the context to urlopen. The second request uses the system trust store, which does not know our CA, so it fails.

We run the server in the background and connect to it with the Python client and with curl. The --cacert option of curl plays the role of the cafile parameter. A connection to 127.0.0.1 works because the address is in the certificate.

$ python https_server.py &
Serving on https://localhost:8443/
$ python https_client.py
200 Hello over TLSv1.3
Without ca.pem: unable to get local issuer certificate
127.0.0.1 - - [30/Oct/2026 22:26:49] "GET / HTTP/1.1" 200 -
$ curl --cacert ca.pem https://127.0.0.1:8443/
Hello over TLSv1.3
127.0.0.1 - - [30/Oct/2026 22:26:49] "GET / HTTP/1.1" 200 -
$ curl https://localhost:8443/
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

The http.server command

Since Python 3.14, the http.server command serves files over HTTPS with the --tls-cert and --tls-key options. If the key is encrypted, the --tls-password-file option names a file with its password. The HTTP server article covers the command in more detail.

$ echo 'Hello there' > hello.txt
$ python -m http.server 8443 --bind 127.0.0.1 --tls-cert server.pem --tls-key server.key &
Serving HTTPS on 127.0.0.1 port 8443 (https://127.0.0.1:8443/) ...
$ curl --cacert ca.pem https://localhost:8443/hello.txt
Hello there
127.0.0.1 - - [30/Oct/2026 22:26:52] "GET /hello.txt HTTP/1.1" 200 -

Keyboard interrupt received, exiting.

Mutual TLS

In mutual TLS, the client presents a certificate too, and the server verifies it. It is used to authenticate services and devices without passwords.

mtls_server.py
import ssl
from http.server import BaseHTTPRequestHandler, HTTPServer


class Handler(BaseHTTPRequestHandler):

    def do_GET(self):

        cert = self.connection.getpeercert()
        subject = dict(item[0] for item in cert['subject'])
        body = f'Hello, {subject["commonName"]}\n'.encode()

        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)


context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile='ca.pem')
context.verify_mode = ssl.CERT_REQUIRED
context.load_cert_chain(certfile='server.pem', keyfile='server.key')

httpd = HTTPServer(('127.0.0.1', 8443), Handler)
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)

print('Serving on https://localhost:8443/')
try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass

The server context trusts our CA through the cafile parameter and requires a client certificate by setting verify_mode to CERT_REQUIRED. The handler reads the client's name from the verified client certificate.

mtls_client.py
import ssl
import urllib.request

context = ssl.create_default_context(cafile='ca.pem')
context.load_cert_chain(certfile='client.pem', keyfile='client.key')

with urllib.request.urlopen('https://localhost:8443/', context=context) as resp:
    print(resp.read().decode().strip())

The client loads its certificate and key into the client context with load_cert_chain; the context sends them when the server asks for a certificate.

Both the Python client and curl with the --cert and --key options get a response. Without a client certificate, the server aborts the handshake with the certificate required alert.

$ python mtls_server.py &
Serving on https://localhost:8443/
$ python mtls_client.py
Hello, alice
127.0.0.1 - - [30/Oct/2026 22:26:53] "GET / HTTP/1.1" 200 -
$ curl --cacert ca.pem --cert client.pem --key client.key https://localhost:8443/
Hello, alice
127.0.0.1 - - [30/Oct/2026 22:26:54] "GET / HTTP/1.1" 200 -
$ curl --cacert ca.pem https://localhost:8443/
curl: (56) OpenSSL SSL_read: error:0A00045C:SSL routines::tlsv13 alert certificate required, errno 0

Source

Python ssl documentation

cryptography X.509 documentation

In this article we have worked with SSL/TLS certificates in Python. We inspected and verified server certificates, created a CSR, issued certificates from a local CA, and used them in an HTTPS server, a client, and with mutual TLS.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.