Python data Encryption Decryption using Cryptography Library
Published February 05, 2022In this post, we are going to look at how to encrypt and decrypt data in Python using the cryptography library. Typically, the cryptography library is used to implement Symmetric-Key encryption. In symmetric key encryption, we use the same key to encrypt and decrypt data. Consequently, we only require one key. This type of encryption and decryption is very easy to use and is regarded as less secure. Anyone with access to the key can decrypt and read the data.
How to perform the Symmetric-Key Encryption
Step 1: First, install the cryptography library in our application. To do this, open your Terminal and execute the following command:
pip install cryptography |
Step 2: Now import the Fernet library using the following code. We are going to use fernet to generate the encryption key
from cryptography.fernet import Fernet |
Step 3: Define the message to be encrypted
message = "I Love Python." |
Step 4: Generate the encryption key using the fernet (key). This key will be used in both encrypting and decrypting
key = Fernet.generate_key() #Instance the Fernet class with the key fernet = Fernet(key) |
Step 5: Encrypt the message using the key generated and output the encrypted text
encMessage = fernet.encrypt(message.encode()) print("original string: ", message) print("encrypted string: ", encMessage) |
Step 6: decrypt the encrypted text using the same encryption key and output the decrypted text
decMessage = fernet.decrypt(encMessage).decode() print("decrypted string: ", decMessage) |
Step 7: Now run your application.
Complete code for Python data encryption
from cryptography.fernet import Fernet message = "I Love Python" key = Fernet.generate_key() fernet = Fernet(key) encMessage = fernet.encrypt(message.encode()) print("original string: ", message) print("encrypted string: ", encMessage) decMessage = fernet.decrypt(encMessage).decode() print("decrypted string: ", decMessage) |
Article Contributed By :
|
|
|
|
258 Views |