Encryption and decryption using password with Fernet














































Encryption and decryption using password with Fernet



Description:
In this article we are going to use our password to generate key, encrypt and decrypt the message.
Programme:
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:
import base64
import os
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:
password = b"password"

Now we will create random 16 byte code using OS:
s = os.urandom(16)

Here we are deriving our key using kdf:
kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=s,
    iterations=390000,
)

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:
f = Fernet(key)

Now we will declare a message:
message=b"Cppsecret.com"

After doing all these we just have to encrypt and decrypt the message:
enc = f.encrypt(message)
dec=f.decrypt(enc)

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

Comments