How to Add a TLS/SSL Certificate in Python Code

Learn how to secure your Python applications with TLS/SSL certificates. Understand the importance of these cryptographic protocols, and grasp how to integrate SSL certificates into Python code using requests library.
  · 6 min read · Updated may 2024 · General Python Tutorials

Welcome! Meet our Python Code Assistant, your new coding buddy. Why wait? Start exploring now!

Introduction

In today's super-connected world, ensuring we send information safely across the internet is a top priority. Have you ever heard of Transport Layer Security (TLS) and Secure Sockets Layer (SSL)? Well, they're cryptographic protocols designed to make sure our interactions over computer networks are kept safe and sound. If you're coding in Python, it's super important to ensure your connection to any external system is secure using these protocols.

In this tutorial, we're going to make it easy for you to understand how to use a TLS/SSL certificate in Python. So, don't worry, we've got you covered! Let's dive in!

Importance of TLS/SSL Certificates

TLS/SSL certificates are critical in preserving data security and privacy. They guarantee that the data moving between your application or website and your users is encrypted, hence, protecting it from unwanted intrusion. These certificates achieve this security by enabling a digital handshake that verifies the identity of the website or server. This procedure safeguards the transmission of confidential data like usernames, passwords, or credit card details, making it an integral aspect of the Internet's framework.

So, how do you acquire these certificates? One approach is to buy an SSL certificate from a Certificate Authority (CA). These entities authenticate and distribute a certificate in your name or in the name of your organization. Recognized globally, they can aid in assuring your users of your application's security.

Prerequisites

Before you can integrate an SSL certificate into your Python code, we need to have the following:

  • A working Python environment: Python version 3.6 or later is recommended.
  • The requests library that allows us to make HTTP requests in our Python code: You can install it using pip: pip install requests.
  • A valid SSL certificate: You can either buy an SSL certificate from a CA or create a self-signed certificate, we will see both in this tutorial.

The Python SSL Library

Python comes with a handy built-in library known as ssl, designed specifically for handling SSL and TLS protocols. Think of it as a wrapper around the OpenSSL library. It offers a more Python-friendly way to interact with many OpenSSL functionalities, including SSL and TLS protocols, X509 certificates, and a variety of cryptographic primitives.

Now, don't worry, in most scenarios, we won't have to mess around directly with the ssl library. Higher-level libraries like requests have us covered. They use ssl behind the scenes, making it a breeze to make secure HTTP requests. It's all about making our coding journey smoother!

Writing a Basic HTTPS Request

Let's start by making a basic HTTPS request using the requests library. This is how we do it:

import requests

response = requests.get('https://www.google.com')
print(response.status_code)

We’re sending a GET request to google.com and printing the status code of the response. Output:

200

Adding an SSL Certificate to the Request

Now, we'll add the SSL certificate to our request. We need the path to the certificate file, which typically ends in .crt or .pem. Here's how we do it:

import requests

response = requests.get('https://www.google.com', verify='/path/to/certificate.pem')
print(response.status_code)

In this code, we're passing the path to the certificate file to the verify parameter. This tells requests to use this certificate when making the HTTPS request.

Dealing with Self-Signed Certificates

There may be times when we think, "Nah, I don't really want to buy an SSL certificate, let's make a self-signed one instead." Now, these DIY certificates do provide the same level of encryption as the ones signed off by a Certificate Authority (CA). But here's the catch - they don't carry the same trust badge, simply because they haven't been given a thumbs-up by an independent authority, so that’s just something to keep in mind. However, if we’re just testing things out or using it internally, these certificates fit the bill perfectly.

Crafting a self-signed certificate is as easy as using OpenSSL from our command line:

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

Note: Make sure you have OpenSSL installed on your machine, before running the above command.

The above command we wrote whips up a fresh RSA key pair along with a self-signed certificate that's valid for 365 days. The certificate will snuggle up in cert.pem, and the private key will reside in key.pem.

We can use this self-signed certificate with requests just like you'd use a CA-signed certificate. Here's how:

import requests

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

So there we have it. Whether we’re testing or using it internally, it's really that simple!

SSL/TLS Client Authentication

In some cases, the server might also require the client (your Python code) to provide a certificate for mutual authentication. This is often done in machine-to-machine communication for added security. You can provide a client certificate like this:

import requests

# make a request to the server that require 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)

In this code, we're passing a tuple to the cert parameter. The first element of the tuple is the path to the client certificate, and the second element is the path to the private key.

The requests library in Python does not provide a built-in mechanism to handle passwords for private keys. When using the cert parameter in requests.get() to provide a client certificate and private key, it assumes that the private key file is not password-protected.

Conclusion

Adding TLS/SSL certificates to Python applications is a key step in safeguarding data transfers. This level of security helps keep sensitive data under wraps by encrypting the info that's being sent between a client and a server. In this piece, we've given you a comprehensive breakdown of how to integrate a TLS/SSL certificate into your Python code, everything from the basics of HTTPS requests and how to handle self-signed certificates to client authentication.

It's vital to always keep your application's security at the top of your list. Whether you opt to purchase an SSL certificate or use a self-signed one for your tests, remember that it's crucial to preserve the privacy and security of your users' data. With this guide in your toolkit, you're all set to bring these security protocols into your Python applications.

Finally, if you're interested in the world of cryptography, then I highly recommend you get our Cryptography with Python eBook; it's a tailored guide for you that includes building 20+ cryptography projects with Python; check it out here.

Happy coding, and remember, security first!

Found the article interesting? You'll love our Python Code Generator! Give AI a chance to do the heavy lifting for you. Check it out!

View Full Code Analyze My Code
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!