In this article we are going to use our password to generate key, encrypt and decrypt the message.
Before starting with code we have to install a python package known as cryptography by writing this in your terminal. pip install cryptography.
After installing the package we have to import some modules from cryptography.
base64: base64 is used to encode and decode the data in which string is converted into byte and then encoded using base 64 module
OS module: This module provide a better way of using operating system.
Hashes: This module return the hashes value of an object.
Kdf: it is the key derivation function.
PBKDF2HMAC: This module helps in deriving a key suitable for encryption.
Now we are going to import the module as shown:
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
After importing the modules we have to create a password as shown:
Now we will create random 16 byte code using OS:
Here we are deriving our key using kdf:
kdf = PBKDF2HMAC(
Now we will generate our key using base64:
key = base64.urlsafe_b64encode(kdf.derive(password))
We will pass the key to Fernet module as shown:
Now we will declare a message:
After doing all these we just have to encrypt and decrypt the message:
enc = f.encrypt(message)
Now we just have to print the data:
print("Encrypted message: ",enc)
print("Decrypted message: ",dec)
Output of the above code is shown below:
Hope you like my article please visit my more article on cppsecret.com