In this tutorial, we will focus on implementing encryption techniques for securing data. Encryption is a crucial aspect of data security, especially when dealing with sensitive information. By the end of this guide, you should be able to understand and implement basic encryption techniques in your applications.
You will learn:
- The basics of encryption
- How to encrypt and decrypt data in Python using the cryptography
library
Prerequisites:
- Basic knowledge of Python
- Python development environment set up
Encryption is the process of converting plain text into an unreadable format (cipher text) using an encryption algorithm and an encryption key. Decryption is the reverse process of converting the cipher text back to plain text using the decryption key.
We will be using Python's cryptography
library which provides cryptographic recipes and primitive.
To install the cryptography library, use pip:
pip install cryptography
In symmetric encryption, the same key is used for encryption and decryption.
from cryptography.fernet import Fernet
# Step 1: Generate a key
key = Fernet.generate_key()
# Step 2: Instance of Fernet with our key
cipher_suite = Fernet(key)
# Step 3: Encrypt a message
cipher_text = cipher_suite.encrypt(b"Hello World")
# Step 4: Decrypt a message
plain_text = cipher_suite.decrypt(cipher_text)
# print the results
print("Cipher Text:", cipher_text)
print("Plain Text:", plain_text.decode())
The Fernet.generate_key()
function is used to generate a secret key. This key is then used to create a Fernet object. The encrypt()
function is used to encrypt the plain text and decrypt()
function to decrypt the cipher text.
In this tutorial, we've learned the basics of encryption and how to use Python's cryptography
library to encrypt and decrypt data. As a next step, you can explore different encryption algorithms and how to use them.
Exercise 1: Write a program that prompts the user for a message, encrypts the message, and prints out the encrypted message.
Exercise 2: Write a program that prompts the user for an encrypted message and a key, decrypts the message with the key, and prints out the decrypted message.
Solution 1:
from cryptography.fernet import Fernet
# Generate a key
key = Fernet.generate_key()
# Instance of Fernet with our key
cipher_suite = Fernet(key)
# Get user input
message = input("Enter a message: ")
# Encrypt the message
cipher_text = cipher_suite.encrypt(message.encode())
print("Encrypted message: ", cipher_text)
Solution 2:
from cryptography.fernet import Fernet
# Get user input
cipher_text = input("Enter the encrypted message: ")
key = input("Enter the encryption key: ")
# Instance of Fernet with our key
cipher_suite = Fernet(key)
# Decrypt the message
plain_text = cipher_suite.decrypt(cipher_text.encode())
print("Decrypted message: ", plain_text.decode())
Remember to keep practicing and exploring more about different encryption algorithms and their implementations.