Web Development

How to Implement TLS/SSL in Python?

By Sean, on July 26, 2023 - 5 min read

With everything available over the internet, cybersecurity has become crucial. When a user tries to access data on the website, the browser communicates with the server and provides information. If this communication is not secure, user data is compromised. 

This is why SSL implementation is important. Implementing SSL in Python is crucial for organizations that use this programming language. Python is a popular programming language that organizations use to build websites, web apps, and mobile applications. With more than 823,004 websites built on Python, it has become an attractive technology.

Python has vulnerabilities causing massive issues for website owners. One way to ensure Python-based websites are secure is to implement SSL/TLS. In this article, we will focus on how to add an SSL certificate to Python. Let us first understand these certificates. Further, how you can implement SSL/TLS protocol?

What is an SSL Certificate?

An SSL (Secure Socket Layer) certificate identifies the publisher and verifies the authenticity of a website. It enables an encrypted connection between a web server and a browser to ensure security for the data exchanged between them. 

An SSL certificate ensures that the information transmitted between the server and the user remains anonymous to any cyber attacker. It encrypts sensitive data like passwords, credit card numbers, and personal information using cryptographic encryptions. 

How does SSL certificate work?

Here is a simplified explanation of how SSL certificates work:

  • When a user tries to establish a secure connection with a server, it sends a request to the server.
  • The server responds to the client’s request by sending its SSL certificate containing the server’s public key and other information.
  • SSL certificate is validated by checking integrity, expiration date, trusted CA, and domain match.
  • The client encrypts a symmetric key with the server’s public key from a trusted certificate and sends it to the server.
  • The server receives the session key from the client and decrypts it using its private key, which matches the public key in the SSL certificate.
  • Secure sessions use a shared key for encryption and decryption, ensuring confidentiality and integrity.

Trusted Certificate Authorities (CAs) issue an SSL certificate after a rigorous validation process to ensure the identity and legitimacy of the website owner. So, getting a certificate for your Python website starts by generating a Certificate Signing request (CSR).

Why is implementing an SSL certificate on Python important?

python

Implementing an SSL certificate on a Python application is crucial for several reasons. It promotes secure data transmission, guards against the exposure of sensitive information, and ensures that only authorized users can access the application. 

Furthermore, SSL certificates build trust with visitors, which is vital for any web application, especially those that entail the exchange of sensitive data. 

How you can install SSL Certificate in Python?

If you are still figuring out how to add an SSL certificate to Python, then there are two effective ways. The first is to generate a self-signed certificate on your server and install it on Python code. The second is to get a Cheap SSL certificate from a trusted SSL provider and install it on Python.

The installation process for a self-signed SSL certificate on Python 

You can generate self-signed SSL certificates using OpenSSL. Use the following command line and generate one for your Python website,

$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -nodes -days 365

You can install OpenSSL from their official website. This command creates a fresh RSA key pair with a self-signed certificate valid for 365 days. 

There will be two types of files,

  • cert. pem for the SSL certificate
  • key.pem for private key pair

Now use the following command line to use a self-signed certificate for user requests,

import requests

response = requests.get('https://self-signed.badssl.com/', verify='our-cert.pem')

print(response.status_code)

It is important to note that the server may require your Python code to provide a certificate. This standard process ensures mutual authentication to establish communication between two systems. 

You can use the following command to provide a client certificate if prompted,

Import requests

# request the server that requires the client to provide a certificate for mutual auth

response = requests.get('https://client.badssl.com/', cert=('our-cert.pem', 'our-key.pem'))

print(response.status_code)

Further, you can create a server to run HTTPS on Python using the self-signed certificate. Use the following command to create the server,

import http.server

import ssl

httpd = http. server.HTTPServer(('localhost,' 443),

http.server.SimpleHTTPRequestHandler)

httpd.socket = ssl.wrap_socket (httpd.socket,

certfile='./certificate.pem', server_side=True, ssl_version=ssl.PROTOCOL_TLS

httpd.serve_forever()

To create a server that uses SSL, first import the SSL and http.server modules in our Python code. Then, call the HTTPServer method on http. server and provide the server’s address and port number. 

After that, wrap the socket with SSL using the wrap_socket method and mention the path to your certificate file. Lastly, run the server, ensure it is secure, and protected from any unauthorized access.

While this process is simple to use, you also need to consider the use case. If you are using a self-signed certificate for internal testing purposes, it is an ideal choice. However, at the same time, buy an SSL certificate from a trusted CA is crucial if you are an enterprise.

This ensures that users’ trust in your brand does not deteriorate, as CA-issued certificates have better security features than self-signed certificates. So, let us understand how to add an SSL certificate to Python issued by a trustworthy CA.

Implementing SSL/TLS on Python through a CA-issued certificate

Implementing SSL/TLS on Python code begins by generating a CSR using OpenSSL. Use the following command line to generate CSR and private keys for your Python website.

openssl req -new -newkey rsa:2048 -nodes -keyout mydomain.com.key -out 

mydomain.com.csr -subj "/CN=mydomain.com"

This command line has,

  • A request to create CSR- req
  • Initiation of new CSR creation- new
  • Definition of the RSA algorithm and key size of 2048 bits for generation of private key-newkey rsa:2048
  • File name to save the CSR-mydomain.com.csr
  • CSR’s subject name, with the Common Name (CN).-subj “/CN=mydomain.com”

But before you use the OpenSSL to generate CSR, here are some key Python libraries that you must have installed on your server,

  • pip install requests
  • pip install certifi
  • pip install ssl
  • pip install pyOpenSSL
  • pip install socketserver

Once you execute the above command line, you will get a private key file and CSR file for your domain, which will be saved, in the directory you define.

Defining the storage for CSR file

Create a directory on your local machine to store CSR and private key files. You can also store private key files in more secure storage that is HSM compliant. Once the files are downloaded on the local machine, copy them and submit them to CA.

Next, CA will verify all the details of your organization, including business location, registration, domain ownership, and more, depending on the type of SSL certificate.

Once CA issues the certificate, a bundle will be sent through email. 

You can download the certificate chain files, which include,

  • Root certificate
  • Intermediate certificate
  • End-user certificate

Install SSL certificate on Python.

Once you have all the certificate files, convert them from the .pem extension to the .crt extension. Further create, an SSL context in Python by using the following code,

import ssl

context = ssl.create_default_context()

context.load_cert_chain(certfile='/path/to/your/certificate.pem', keyfile='/path/to/your/private.key')

Once you execute the command, an SSL certificate will be installed. The next step is to verify the SSL certificate installation on the website.

Verify the Installation of the SSL certificate on the Python

Analyze the certificate chain on the server and ensure the certificate is active. Extract the certificate chain by using the following command,

import ssl

import socket

hostname = 'mydomain.com' # Replace with your domain name

context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:

with context.wrap_socket(sock, server_hostname=hostname) as ssock:

chain = ssock.getpeercert(chain=True)

print(chain)

In a nutshell

With increased cyberattacks and ever-changing threats, ensuring better security for your websites is crucial. Python does come with many security features, but there is no denying that SSL certificates are essential.

We have discussed implementing SSL in Python for self-signed certificates and CA-issued ones. You can use the method, which suits your project. 

Sean