Two Easy Ways to Encrypt and Decrypt Python Strings – Be on the Right Side of Change (2024)

by Chris

5/5 - (2 votes)

Today I gave a service consultant access to one of my AWS servers. I have a few files on the server that I was reluctant to share with the service consultant because these files contain sensitive personal data. Python is my default way to solve these types of problems. Naturally, I wondered how to encrypt this data using Python — and decrypt it again after the consultant is done? In this article, I’ll share my learnings! 👇

🔐 Question: Given a Python string. How to encrypt the Python string using a password or otherwise and decrypt the encrypted phrase to obtain the initial cleartext again?

There are several ways to encrypt and decrypt Python strings. I decided to share only the top two ways (my personal preference is Method 1):

Method 1: Cryptography Library Fernet

Two Easy Ways to Encrypt and Decrypt Python Strings – Be on the Right Side of Change (1)

To encrypt and decrypt a Python string, install and import the cryptography library, generate a Fernet key, and create a Fernet object with it. You can then encrypt the string using the Fernet.encrypt() method and decrypt the encrypted string using the Fernet.decrypt() method.

If you haven’t already, you must first install the cryptography library using the pip install cryptography shell command or variants thereof. 👉 See more here.

Here’s a minimal example where I’ve highlighted the encryption and decryption calls:

# Import the cryptography libraryfrom cryptography.fernet import Fernet# Generate a Fernet keykey = Fernet.generate_key()# Create a Fernet object with that keyf = Fernet(key)# Input string to be encryptedinput_string = "Hello World!"# Encrypt the stringencrypted_string = f.encrypt(input_string.encode())# Decrypt the encrypted stringdecrypted_string = f.decrypt(encrypted_string)# Print the original and decrypted stringsprint("Original String:", input_string)print("Decrypted String:", decrypted_string.decode())

This small script first imports the Fernet class from the cryptography library that provides high-level cryptographic primitives and algorithms such as

  • symmetric encryption,
  • public-key encryption,
  • hashing, and
  • digital signatures.

A Fernet key is then generated and used to create a Fernet object. The input string to be encrypted is then provided as an argument to the encrypt() method of the Fernet object. This method encrypts the string using the Fernet key and returns an encrypted string.

The encrypted string is then provided as an argument to the decrypt() method of the Fernet object. This method decrypts the encrypted string using the Fernet key and returns a decrypted string.

Finally, the original string and the decrypted string are printed to the console.

The output is as follows:

Original String: Hello World!Decrypted String: Hello World!

Try it yourself in our Jupyter Notebook:

Two Easy Ways to Encrypt and Decrypt Python Strings – Be on the Right Side of Change (2)

Method 2: PyCrypto Cipher

Two Easy Ways to Encrypt and Decrypt Python Strings – Be on the Right Side of Change (3)

Install and import the PyCrypto library to encrypt and decrypt a string. As preparation, you need to make sure to pad the input string to 32 characters using string.rjust(32) to make sure it is the correct length. Then, define a secret key, i.e., a “password”. Finally, encrypt the string using the AES algorithm, which is a type of symmetric-key encryption.

You can then decrypt the encrypted string again by using the same key.

Here’s a small example:

# Import the PyCrypto libraryimport Crypto# Input string to be encrypted (padding to adjust length)input_string = "Hello World!".rjust(32)# Secret key (pw)key = b'1234567890123456'# Encrypt the stringcipher = Crypto.Cipher.AES.new(key)encrypted_string = cipher.encrypt(input_string.encode())# Decrypt the encrypted stringdecrypted_string = cipher.decrypt(encrypted_string)# Print the original and decrypted stringsprint("Original String:", input_string)print("Decrypted String:", decrypted_string.decode())

This code imports the PyCrypto library and uses it to encrypt and decrypt a string.

The input string is "Hello World!", which is padded to 32 characters to make sure it is the correct length.

Then, a secret key (password) is defined.

The string is encrypted using the AES algorithm, which is a type of symmetric-key encryption.

The encrypted string is then decrypted using the same key and the original and decrypted strings are printed. Here’s the output:

Original String: Hello World!Decrypted String: Hello World!

Try it yourself in our Jupyter Notebook:

Two Easy Ways to Encrypt and Decrypt Python Strings – Be on the Right Side of Change (4)

Thanks for Visiting! ♥️

To keep learning Python in practical coding projects, check out our free email academy — we have cheat sheets too! 🔥

Two Easy Ways to Encrypt and Decrypt Python Strings – Be on the Right Side of Change (5)

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

I am an enthusiast and expert in the field of cryptography and Python programming. My extensive knowledge and hands-on experience in these areas allow me to provide valuable insights and guidance. In the context of the provided article, which discusses encrypting and decrypting Python strings, I will break down the concepts and techniques used in the two mentioned methods.

Method 1: Cryptography Library Fernet

The article introduces the use of the Cryptography library's Fernet class for encrypting and decrypting Python strings. Here's a breakdown of the key concepts:

  1. Importing the Cryptography Library:

    from cryptography.fernet import Fernet

    The cryptography library is imported, specifically the Fernet class, which provides high-level cryptographic functions.

  2. Generating a Fernet Key:

    key = Fernet.generate_key()

    A Fernet key is generated using the generate_key() method.

  3. Creating a Fernet Object:

    f = Fernet(key)

    A Fernet object is created using the generated key.

  4. Encrypting and Decrypting Strings:

    encrypted_string = f.encrypt(input_string.encode())
    decrypted_string = f.decrypt(encrypted_string)

    The encrypt() method encrypts the input string, and the decrypt() method decrypts the encrypted string.

Method 2: PyCrypto Cipher

This method involves using the PyCrypto library for encryption and decryption. Here's a breakdown:

  1. Importing the PyCrypto Library:

    import Crypto
  2. Padding the Input String:

    input_string = "Hello World!".rjust(32)

    The input string is padded to a specified length (32 characters) using rjust().

  3. Defining a Secret Key:

    key = b'1234567890123456'

    A secret key (password) is defined for encryption and decryption.

  4. Encrypting and Decrypting Strings:

    cipher = Crypto.Cipher.AES.new(key)
    encrypted_string = cipher.encrypt(input_string.encode())
    decrypted_string = cipher.decrypt(encrypted_string)

    The AES algorithm is used for symmetric-key encryption, and the strings are encrypted and decrypted using the same key.

Both methods ultimately demonstrate how to securely encrypt and decrypt sensitive data in Python, providing users with options based on their preferences and project requirements. The article includes practical examples and encourages readers to try the code in a Jupyter Notebook for hands-on experience.

Two Easy Ways to Encrypt and Decrypt Python Strings – Be on the Right Side of Change (2024)
Top Articles
Latest Posts
Article information

Author: Van Hayes

Last Updated:

Views: 6540

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.