What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

How to use SSL Certificate with Python Code?

  • Jul 05, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Komal Gupta
How to use SSL Certificate with Python Code?

In today’s digital landscape, as people's reliance on the Internet for daily activities like shopping, banking, and communication is increasing day by day, securing websites is of paramount importance for protecting them from cyber attacks like data breaching, phishing attacks, etc. That’s where SSL comes into play.

Today, we will look over one of the effective ways to secure your websites from cyber attacks by implementing SSL certificates with Python. We will also explore what an SSL certificate is, and why it is crucial for your website's security.

What is an SSL Certificate?

A Secure Socket Layer or SSL is a cryptographic technology that guarantees that information transmitted between a server and a browser stays encrypted. Basically, it allows for safe internet communication. The basic aim of SSL certificates is to prove a website's validity and trustworthiness.

These are issued by reputable Certificate Authorities (CAs) and include information about the website's owner. When a web browser connects to a website protected by an SSL/TLS certificate, it authenticates the certificate and establishes a secure encrypted connection.

While SSL was once extensively used, Transport Layer Security (TLS), an improved version of SSL, is now the current standard for secure communication.

Businesses can facilitate the usage of HTTPS protocols by putting SSL/TLS certificates on their websites. It encrypts communication between the web server and the browser, ensuring that sensitive information such as user credentials, and other private data stays private during transmission.

Why is SSL important for a Website?

SSL offers numerous important advantages for the security of your website:

  • SSL encrypts the communication between the server and the browser, ensuring the privacy of sensitive information such as login credentials, personal information, and financial transactions.

  • Search engines prefer websites with SSL certificates because they value user security. Having an SSL certificate can improve the ranking and reputation of your website.

  • SSL certificates validate your website's identity, giving users trust that they are communicating with a legitimate site rather than a malevolent impostor.

  • It is a protocol that combines HTTP with the Secure Socket Layer (SSL)/Transport Layer Security (TLS).

What are the types of SSL?

Let's discuss all the variations of SSL we have:

  1. Domain Validated SSL Certificates (DV): They are mostly used to secure small to medium-sized websites because they require minimal validation processes. To obtain a DV certificate, you must first demonstrate domain ownership to the CA and then pass the email validation process.

  2. Organization Validated (OV): Here, CAs give certificates after verifying an organization's identity in addition to domain ownership, offering increased confidence and legal existence, making them perfect for organizations that handle sensitive information.

  3. Extended Validation (EV): These SSL certificates provide the most significant level of security certification by offering extremely secure encryption. CAs use additional legal tests to confirm domain ownership and the identity of the organization.

  4. A wildcard: An SSL certificate is a single certificate that secures a domain and all of its subdomains by utilizing a wildcard character (*) in the domain name field. It is also cost-effective, streamlines, and provides trust indications for secure communication.

  5. Multi-domain certificates: Also known as SAN or UCC certificates, protect several domains and subdomains with a single certificate. They provide flexibility, interoperability, and security. They are perfect for businesses that have many websites or applications.

How to Get an SSL Certificate?

To request an SSL certificate, send the CSR to a trustworthy Certificate Authority (CA). The CA will validate your information before issuing the certificate. You should get an SSL certificate from authorized entities only.

Then, install the SSL certificate on your web server once you have received it, and it will secure the connection between the user and the server, as represented by the padlock icon. The procedure differs based on the configuration of your server.

How to Secure Websites with Python SSL?

The first step in using a TLS/SSL certificate in Python is to select the correct Certificate Authority (CA). These CAs are reputable organizations that issue secure certificates. They will need details about your domain and organization in order to issue a certificate.

SSL certificates use an encryption method known as asymmetric encryption, which comprises two key pairs: a private key and a public key.

Asymmetric encryption employs one key for encryption and another for decryption. This is important to understand since generating a CSR and private key pair is the first step in using a TLS/SSL certificate in Python.

It's worth noting that the Python SSL module also supports outdated and deprecated protocols for backward compatibility. However, developers should avoid using these outmoded protocols in favor of the TLS (Transport Layer Security) protocol, which has mostly supplanted SSL.

To emphasize the importance of this, MITRE has published a Common Weakness Enumeration (CWE) that exposes the issue of employing flawed or hazardous cryptographic methods. 

Installing Libraries: 

pip install requests

pip install certifi

pip install ssl

pip install pyOpenSSL

pip install socketserver

Step1: Creating a CSR Using OpenSSL, create a private key and a Certificate Signing Request (CSR):

openssl req -new -newkey rsa:2048 -nodes -keyout www.favtutor.com.key -out www.favtutor.com.csr -subj "/CN=www.favtutor.com"

 The command is broken down as follows:

  • openssl: The OpenSSL command-line tool.

  • req: Indicates that you wish to create a CSR.

  • -new: Indicates the creation of a new CSR.

  • -newkey rsa:2048: Defines the RSA algorithm and a key length of 2048 bits for the generation of private keys.

  • -nodes: Generates a private key without passphrase encryption for convenience (remove this option if you want the private key to be encrypted with a password).

  • -keyout www.favtutor.com.key: The filename to which the private key should be saved.

  • Check out www.favtutor.com.csr: The filename to which the CSR should be saved.

  • -subj "/CN=www.favtutor.com": Sets the CSR's subject name, with the Common Name (CN) reflecting the certificate's domain.

After executing this command, you will have the private key file (www.favtutor.com.key) and the CSR file (www.favtutor.com.csr) for the domain "www.favtutor.com" which will be saved in the current working directory. Similarly, you can create the private key and CSR file for any of your domains.

Step 2: Store the CSR File

Create a directory locally on your machine with the certificate file on top once you have the certificate and chain file. The new directory should be named "favtutor.com.combinecd.cert." Send an encrypted private key to a CA together with the CSR so that they may confirm your identity as a Python developer or requestor before issuing the certificate.

Step 3: Python SSL Certificate Installation

After obtaining the certificate, rename it as ‘certificate.pem’ from ‘certificate.crt’. Then write a python code to create an SSL context.

import ssl

context = ssl.create_default_context()

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

 
Step 4: Verifying the Installation

Examine the SSL certificate chain given by the server to ensure that the SSL certificate is being used. To extract the SSL certificate chain supplied by the server, use Python's SSL module:

import ssl

import socket

hostname = 'www.favtutor.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)

 

The provided code snippet can be broken down into the following steps:

  • Import the necessary modules (SSL and socket).

  • Put the desired domain name in the hostname variable.

  • Using SSL, create an SSL context.create_default_context().

  • Using socket, connect to the hostname and port 443.create_connection().

  • Using context, encrypt the socket with SSL/TLS.wrap_socket(), with the server hostname supplied for verification.

  • ssock.getpeercert(chain=True) returns the server certificate chain.

  • To see the certificates involved in the secure connection, print the obtained certificate chain.

Conclusion

I hope that you have understood the importance of SSL certificates and how to implement them using Python. Further, it has to be noted that there are different algorithms available to create private keys and CSR files with the help of different frameworks and libraries in Python. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Komal Gupta
I am a driven and ambitious individual who is passionate about programming and technology. I have experience in Java, Python, and machine learning, and I am constantly seeking to improve and expand my knowledge in these areas. I am an AI/ML researcher. I enjoy sharing my technical knowledge as a content writer to help the community.