Data Encryption is the process through which data is encoded so that it remains hidden from or inaccessible to unauthorized users. In this tutorial, I’ll show you how to How to Encrypt and Decrypt Data Using Python.
It helps protect private information, sensitive data like password, credit card details, and can enhance the security of communication between client apps and servers.
For the data encryption, we need one python module called cryptography. cryptography is a package that provides cryptographic recipes and primitives to Python developers. cryptography documentation.
To use this module we have to first install it. so open the terminal and type,
pip install cryptography
Now we successfully installed this module. but to use this we have to install it. In addition we need only Fernet from this module so we only import it. let’s see how.
from cryptography.fernet import Fernet
Just like this. Now we need a key. In cryptography, a ‘key’ is a piece of information used in combination with an algorithm to transform plaintext into encryption. Let’s generate the key first.
key = Fernet.generate_key() f = Fernet(key)
Now we successfully created a key. This generate_key() function generates random keys each time when we run the code. So, it’s better for you to store this key in a separate text file. Now we successfully generated a key so let’s encrypt the data.
message = "This is the password" encrypted = f.encrypt(message.encode()) print(encrypted) decrypted = f.decrypt(encrypted) print(decrypted)
Here message is our string which we have to encrypt. encrypt() function takes string as ASCII value of single bytes. That’s why we have to encode the string. Let’s have a look at the output.
As I told before key will be different each time. Here is the complete code:
from cryptography.fernet import Fernet key = Fernet.generate_key() f = Fernet(key) message = "This is the password" encrypted = f.encrypt(message.encode()) print(encrypted) decrypted = f.decrypt(encrypted) print(decrypted)
This is How to Encrypt and Decrypt Data Using Python.
Post you may like: How to Get Wikipedia Results Using Python (GUI)