Symmetric encryption with the fernet package

Fernet is an implementation of symmetric encryption and guarantees that an encrypted message cannot be manipulated or read without the key.

For generating the key, we can use the generate_key() method from the Fernet interface.

You can find the following code in the encrypt_decrypt.py file inside the cryptography folder:

from cryptography.fernet import Fernetkey = Fernet.generate_key()cipher_suite = Fernet(key)print("Key "+str(cipher_suite))message = "Secret message"cipher_text = cipher_suite.encrypt(message)plain_text = cipher_suite.decrypt(cipher_text)print("\n\nCipher text: "+cipher_text)print("\n\nPlain text: "+plain_text)

This is the output of the previous script:

Get Mastering Python for Networking and Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.