Coding Symmetric Encryption

We will use Python's cryptography package, in this section, to demonstrate symmetric encryption. It is a comprehensive package that implements many cryptographic algorithms, such as symmetric ciphers and different message digests. When using it for the first time, we first need to install it using the pip command:

!pip install cryptography

Once installed, we can now use the package to implement symmetric encryption, as follows:

  1. First, let's import the packages we need:
import cryptography as crypt
from cryptography.fernet import Fernet
  1. Let's generate the key:

  1. Now, let's open the key:
file = open('mykey.key', 'wb')
file.write(key)
file.close()
  1. Using the key, let's now try to encrypt the message:

file = open('mykey.key', 'rb')
key = file.read()
file.close()
  1. Now, let's decrypt the message using the same key:
from cryptography.fernet import Fernet
message = "Ottawa is really cold".encode()

f = Fernet(key)
encrypted = f.encrypt(message)
  1. Let's decrypt the message and assign it to a variable named decrypt:
decrypted = f.decrypt(encrypted)
  1. Let's now print the decrypt variable to verify whether we are able to get the same message:

Let's look at some of the advantages of symmetric encryption.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.168.16