How to encrypt and decrypt data in Python (2024)

'; var adpushup = adpushup || {}; adpushup.que = adpushup.que || []; adpushup.que.push(function() { adpushup.triggerAd(ad_id); });

Introduction

What is cryptography? Cryptography deals with the conversion of plain text into cipher text which is called encryption of data and cipher text back to plain text which is called decryption of data.

We will be using the fernet module in the cryptography package to encrypt and decrypt data using Python. While using the fernet module, a unique key is generated without which you cannot read or manipulate the encrypted data.

Now that you know what we will be dealing with, let’s get started.

Getting Started

The cryptography module does not come packaged with Python, which means you will have to install it using the pip package manager. To do so, launch your terminal and type in the code below.

pip install cryptography

Once you have the package downloaded and installed, you can import its modules.

We will be using the fernet module to encrypt and decrypt data. So, let us import it into the Python script.

from cryptography.fernet import Fernet

Note − Make sure you get the capitalization’s correct.

You are all set to start writing your script.

Generating a Key

In order to start encrypting data, you must first create a fernet key.

key = Fernet.generate_key()f = Fernet(key)

In the above lines, we generated a key using the generate_key() method and then assigned that key to a variable “f” in the next line.

And that’s it, you now have a key stored in a variable ready to be used.

We can print the key and store it, if needed. Make sure to use the decode function while printing.

print(key.decode())

Output

Bq64GE−−93K1RVro4go1frN−8twBSvXdbCPSPLIKz9U=

Encrypting Data

In order to encrypt data from the above key, you must use the encrypt method.

encrypted_data = f.encrypt(b"This message is being encrypted and cannot be seen!")

And that’s it, the above sentence has been encrypted.

To view your encrypted message, you must print it.

print(encrypted_data)

Output

b'gAAAAABgILy91p_wqMntdT3mDkh0IBXSLjuBMQAfnGZAFkZCX1U6Q7TU2PthgFBwVz0QbKXpuNTHRzAgbdDV4zfuuzkGCXqVD--xJdkTycKH2iurC_oqHySLc9xJEXz93LkhTbKUa5HCxfJtB-Um_YkxqjclftXXZQ=='

Note − We had the b before the sentence in order to convert it into byte format. You can choose use the encode() method instead as well.

Decrypting Data

Now that you have the cipher text, let us see how we can convert it back to plain readable text.

We can achieve decryption using the decrypt method in the fernet module.

decrypted_data = f.decrypt(encrypted_data) # f is the variable that has the value of the key.print(decrypted_data)

Output

b'This message is being encrypted and cannot be seen!'

Note − If you look at the above output, you can notice that there is b’ before the printed plaintext, this is because encrypted data is being converted back into byte format. In order to get just the plain text, we need to use the decode function.

print(decrypted_data.decode())

Output

This message is being encrypted and cannot be seen!

Note − You can encrypt and decrypt data using the same key. That is, if you print the value of the key and save it. You can use the same key by assigning it to a variable. Example −>

f = Fernet(Bq64GE--93K1RVro4go1frN-8twBSvXdbCPSPLIKz9U=) # Value of an actual key is given.

Example

from cryptography.fernet import Fernetkey = Fernet.generate_key()print("Key : ", key.decode())f = Fernet(key)encrypted_data = f.encrypt(b"This message is being encrypted and cannot be seen!")print("After encryption : ", encrypted_data)decrypted_data = f.decrypt(encrypted_data)print(decrypted_data)print("After decryption : ", decrypted_data.decode())

Output

Key : u4dM7xw8sNNU3Rm_lwDbixudWSeaM0Z4TTDdQNKsouI=After encryption : b'gAAAAABgIL3_qbfM_oMgQn653gpk6a7hqxXiR0dl0vrmOmqnr5b6MqrsjGkK1IknxMLLtOCq6_YlX4x3nBedbZqtCqy4os55pttrl-pBO6-dJf6kVP50IpIaKSXbpAsuWl4h_2o_E-4YEqZ5kkgxWrwnqojmkMyuSQ=='b'This message is being encrypted and cannot be seen!'After decryption : This message is being encrypted and cannot be seen!

Conclusion

You have now learnt to encrypt and decrypt data using the cryptography package in Python.

You can even save the key as a .txt file and then retrieve it to encrypt and store password or decrypt password from database to verify if it matches. There are various other cases where you can use this, be it a mini−project or a large scale project.

For more information on the cryptography module, you can read through their official documentation at − https://pypi.org/project/cryptography/

Updated on: 11-Feb-2021

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started

How to encrypt and decrypt data in Python (31)

Advertisem*nts

'; adpushup.triggerAd(ad_id); });

How to encrypt and decrypt data in Python (2024)

FAQs

How to encrypt and decrypt data 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

Which algorithm is best for encryption and decryption in Python? ›

Some of the most common and widely used algorithms are AES, RSA, and Fernet. AES is a symmetric algorithm that uses the same key for encryption and decryption, and it is fast and efficient for large data.

How do you encrypt and decrypt data? ›

To encrypt more than a small amount of data, symmetric encryption is used. A symmetric key is used during both the encryption and decryption processes. To decrypt a particular piece of ciphertext, the key that was used to encrypt the data must be used.

What is the algorithm to encrypt and decrypt passwords? ›

Hash function: The algorithm that uses the key to create password encryption and decryption. A hash function is essentially a piece of code that runs every time someone saves a password or logs into an application. Hash: A random series of numbers and letters representing your password.

What uses two keys to encrypt and decrypt data? ›

Asymmetric cryptography involves a pair of keys to encrypt and decrypt data. The two participants in the asymmetric encryption workflow are the sender and the receiver. Each has its own pair of public and private keys.

Can hackers decrypt encrypted data? ›

Can hackers see encrypted data? No, hackers cannot see encrypted data, as it is scrambled and unreadable until the encryption key (or passphrase) is used to decrypt it. However, if a hacker manages to obtain the encryption key or crack the encryption algorithm, then they can gain access to the data.

How to write an encryption algorithm in Python? ›

Algorithm for Cryptography with Python
  1. Make a list of all the alphabet.
  2. Create a function that takes the text and a number as a parameter.
  3. Move through each element.
  4. If it's a space add it to the new list as it is.
  5. Take out the position of the character it should replace with.
  6. Join.
  7. Display the encrypted text.

What is the toughest encryption algorithm? ›

The algorithm provides 128-bit block encryption and has been designed to supports key sizes of 128, 192 and 256 bits. AES 256-bit encryption is the strongest and most robust encryption standard that is commercially available today.

What is the most efficient encryption algorithm? ›

The Advanced Encryption Standard (AES) is the trusted standard algorithm used by the United States government, as well as other organizations. Although extremely efficient in the 128-bit form, AES also uses 192- and 256-bit keys for very demanding encryption purposes.

What is the best way to encrypt data? ›

The two most widely used methods for data encryption are public key, also known as asymmetric encryption, and private key, or symmetric encryption.

What is the formula of encryption and decryption? ›

The encryption formula is En(x) = (x + n) mod 26 and the Decryption formula is Dn(x) = (x – n) mod 26. While it's easy to implement but it can't withstand the modern era. As computers can break it easily.

How do I manually encrypt data? ›

How to encrypt a file
  1. Right-click (or press and hold) a file or folder and select Properties.
  2. Select the Advanced button and select the Encrypt contents to secure data check box.
  3. Select OK to close the Advanced Attributes window, select Apply, and then select OK.

What is the easiest encryption algorithm? ›

Asymmetric Encryption

As it uses only one key, it's a simpler method of encryption.

What is the 3 way encryption algorithm? ›

In cryptography, 3-Way is a block cipher designed in 1994 by Joan Daemen. It is closely related to BaseKing; the two are variants of the same general cipher technique. 3-Way has a block size of 96 bits, notably not a power of two such as the more common 64 or 128 bits. The key length is also 96 bits.

What are the four 4 most secure encryption techniques? ›

Now let's look at seven common methods of encryption that you can use to safeguard sensitive data for your business.
  1. Advanced Encryption Standard (AES) ...
  2. Triple Data Encryption Standard (TDES) ...
  3. Rivest Shamir Adleman (RSA) ...
  4. Blowfish. ...
  5. Twofish. ...
  6. Format-Preserving Encryption (FPE) ...
  7. Elliptic Curve Cryptography (ECC)
Nov 29, 2022

How to make a Python encryption? ›

Algorithm for Cryptography with Python
  1. Make a list of all the alphabet.
  2. Create a function that takes the text and a number as a parameter.
  3. Move through each element.
  4. If it's a space add it to the new list as it is.
  5. Take out the position of the character it should replace with.
  6. Join.
  7. Display the encrypted text.

How to encode and decode a string in Python? ›

In conclusion, to encode and decode data in Python, choose an appropriate encoding scheme, use . encode() and . decode() methods, transmit or store encoded data, validate your decoded data, and handle errors.

How to encrypt and decrypt a message using RSA algorithm Python? ›

Here the public key is {e, n} and private key is {d, n}. If M is the plain text then the cipher text C = (M^e) mod n. This is how data is encrypted in RSA algorithm. Similarly, for decryption, the plain text M = (C^d) mod n.

Top Articles
Preparing for the theory test
How smart ESG investing could boost portfolio returns | J.P. Morgan Private Bank U.S.
Golden Abyss - Chapter 5 - Lunar_Angel
Skylar Vox Bra Size
Cash4Life Maryland Winning Numbers
Wizard Build Season 28
Coindraw App
Tv Guide Bay Area No Cable
Fully Enclosed IP20 Interface Modules To Ensure Safety In Industrial Environment
Sam's Club Gas Price Hilliard
Western Razor David Angelo Net Worth
Slay The Spire Red Mask
Everything You Need to Know About Holly by Stephen King
Shuiby aslam - ForeverMissed.com Online Memorials
Nene25 Sports
Fool’s Paradise movie review (2023) | Roger Ebert
Highland Park, Los Angeles, Neighborhood Guide
Swedestats
Abby's Caribbean Cafe
Welcome to GradeBook
Nhl Tankathon Mock Draft
Sec Baseball Tournament Score
Accuweather Minneapolis Radar
Page 2383 – Christianity Today
As families searched, a Texas medical school cut up their loved ones
Sensual Massage Grand Rapids
Section 408 Allegiant Stadium
Ncal Kaiser Online Pay
Best Restaurants Ventnor
Deepwoken: Best Attunement Tier List - Item Level Gaming
R/Orangetheory
Abga Gestation Calculator
Wake County Court Records | NorthCarolinaCourtRecords.us
Smartfind Express Henrico
Poster & 1600 Autocollants créatifs | Activité facile et ludique | Poppik Stickers
Santa Cruz California Craigslist
Mars Petcare 2037 American Italian Way Columbia Sc
Tillman Funeral Home Tallahassee
Electronic Music Duo Daft Punk Announces Split After Nearly 3 Decades
Complete List of Orange County Cities + Map (2024) — Orange County Insiders | Tips for locals & visitors
Giovanna Ewbank Nua
3 bis 4 Saison-Schlafsack - hier online kaufen bei Outwell
21 Alive Weather Team
Pathfinder Wrath Of The Righteous Tiefling Traitor
Citymd West 146Th Urgent Care - Nyc Photos
Catchvideo Chrome Extension
Haunted Mansion (2023) | Rotten Tomatoes
Tommy Bahama Restaurant Bar & Store The Woodlands Menu
Otter Bustr
32 Easy Recipes That Start with Frozen Berries
Latest Posts
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 6551

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.