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)

FAQs

How do you encrypt and decrypt code in Python? ›

Steps:
  1. Import rsa library.
  2. Generate public and private keys with rsa. ...
  3. Encode the string to byte string.
  4. Then encrypt the byte string with the public key.
  5. Then the encrypted string can be decrypted with the private key.
  6. The public key can only be used for encryption and the private can only be used for decryption.
Jun 8, 2022

What are two different keys used one to encrypt another to decrypt? ›

Asymmetric encryption uses the notion of a key pair: a different key is used for the encryption and decryption process. One of the keys is typically known as the private key and the other is known as the public key.

Which type of encryption uses two keys that encrypt and decrypt data? ›

Asymmetric encryption uses a mathematically related pair of keys for encryption and decryption: a public key and a private key.

How do you encrypt a string key? ›

encrypt() Encrypts a string. Uses a symmetric key-based algorithm, in which the same key is used to encrypt and decrypt a string. The security of the encrypted string depends on maintaining the secrecy of the key.

How do I encrypt and decrypt code? ›

Encryption: scrambling the data according to a secret key (in this case, the alphabet shift). Decryption: recovering the original data from scrambled data by using the secret key. Code cracking: uncovering the original data without knowing the secret, by using a variety of clever techniques.

What is an example of encryption in Python? ›

One early example of a simple encryption is the “Caesar cipher,” named for Roman emperor Julius Caesar because he used it in his private correspondence. The method is a type of substitution cipher, where one letter is replaced by another letter some fixed number of positions down the alphabet.

What are the two encryption methods? ›

What are the different types of encryption? The two main kinds of encryption are symmetric encryption and asymmetric encryption. Asymmetric encryption is also known as public key encryption.

What is two-way encryption? ›

Encryption is a two-way function where data is passed in as plaintext and comes out as ciphertext, which is unreadable. Since encryption is two-way, the data can be decrypted so it is readable again.

Which is an encryption technique with 2 keys? ›

Symmetric encryption involves using a single key to encrypt and decrypt data, while asymmetric encryption uses two keys - one public and one private - to encrypt and decrypt data.

What is the two key encryption method? ›

Public key cryptography is a method of encrypting or signing data with two different keys and making one of the keys, the public key, available for anyone to use. The other key is known as the private key. Data encrypted with the public key can only be decrypted with the private key.

What is used for both encryption and decryption? ›

Symmetric encryption uses the same key to both encrypt and decrypt data, while asymmetric encryption uses two different keys for the same purpose. Symmetric encryption is faster and easier to use than asymmetric encryption, but it is less secure. If the key is compromised, the data can be easily decrypted.

Which key is used to encrypt and decrypt the data? ›

The two keys are called the “public key” and the “private key” of the user. The network also has a public key and a private key. The sender uses a public key to encrypt the message. The recipient uses its private key to decrypt the message.

How to encrypt password string in Python? ›

In Python with the help of maskpass() module and base64() module we can hide the password of users with asterisk(*) during input time and then with the help of base64() module it can be encrypted.

How are strings encrypted? ›

String Encryption is the process by which PreEmptive Protection™ DashO™ replaces strings in the constant pools of processed classes with encrypted values that are then decrypted in the running application, making it more difficult to read the string constants via static analysis of the code.

How do I manually encrypt a text? ›

Type Ctrl + Shift + X on your keyboard to encrypt the selected text.

Can Python code be encrypted? ›

As of Allplan 2022-1, it's possible to encrypt the . py-files containing source code. The encrypted files are unreadable and allow to protect the developer's copyrights.

What does "encrypt" mean in Python? ›

It is a process of converting information into some form of a code to hide its true content. The only way to access the file information then is to decrypt it. The process of encryption/decryption is called cryptography. Let's see how we can encrypt and decrypt some of our files using Python.

How to encrypt a message with a key in Python? ›

You're prompted to enter the 'message' and the 'key' (a number from 0 to 25). The 'encrypt()' function is summoned, and your message is encrypted. It's like locking your message in a safe. Then, the 'decrypt()' function is called, and the safe is unlocked, revealing your original message.

Top Articles
Types Of Bad Faith Insurance Practices| CA Insurance Attorney
14 Proven Ways to Make $2,000-$3,000 Per Month in Passive Income
Cpmc Mission Bernal Campus & Orthopedic Institute Photos
Caesars Rewards Loyalty Program Review [Previously Total Rewards]
Mackenzie Rosman Leaked
What Happened To Dr Ray On Dr Pol
America Cuevas Desnuda
Kristine Leahy Spouse
RuneScape guide: Capsarius soul farming made easy
P2P4U Net Soccer
What is international trade and explain its types?
Conduent Connect Feps Login
Valentina Gonzalez Leak
What Time Chase Close Saturday
Love In The Air Ep 9 Eng Sub Dailymotion
Gdlauncher Downloading Game Files Loop
Alexander Funeral Home Gallatin Obituaries
Harem In Another World F95
The best TV and film to watch this week - A Very Royal Scandal to Tulsa King
Halo Worth Animal Jam
Amazing deals for Abercrombie & Fitch Co. on Goodshop!
Craigslist Clinton Ar
Dwc Qme Database
Wics News Springfield Il
A Cup of Cozy – Podcast
Airline Reception Meaning
Egusd Lunch Menu
Dal Tadka Recipe - Punjabi Dhaba Style
Happy Shuttle Cancun Review
Sam's Club Gas Price Hilliard
What Is The Lineup For Nascar Race Today
Citibank Branch Locations In Orlando Florida
Mkvcinemas Movies Free Download
Colin Donnell Lpsg
Craigslist Gigs Norfolk
Verizon TV and Internet Packages
Tas Restaurant Fall River Ma
Compress PDF - quick, online, free
Clark County Ky Busted Newspaper
Reborn Rich Ep 12 Eng Sub
Ukg Dimensions Urmc
That1Iggirl Mega
Toth Boer Goats
Michael Jordan: A timeline of the NBA legend
Check From Po Box 1111 Charlotte Nc 28201
Gfs Ordering Online
Doublelist Paducah Ky
Citymd West 146Th Urgent Care - Nyc Photos
60 Days From May 31
2000 Fortnite Symbols
Gameplay Clarkston
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.