How to encrypt a file in Python
How to encrypt a file in Python.
Here is a step-by-step tutorial on how to encrypt a file in Python:
Step 1: Import the necessary libraries
First, we need to import the necessary libraries for encryption. In this tutorial, we will be using the cryptography library, which provides a suite of cryptographic recipes and algorithms.
from cryptography.fernet import Fernet
Step 2: Generate a key
To encrypt and decrypt a file, we need a key. The key is used to perform the encryption and decryption operations. In this example, we will use the Fernet class from the cryptography library to generate a key.
key = Fernet.generate_key()
Step 3: Save the key
Next, we need to save the key to a file so that we can use it for encryption and decryption later. You can choose a filename and location of your choice to save the key.
with open('key.txt', 'wb') as key_file:
key_file.write(key)
Step 4: Load the key
Before we can encrypt or decrypt a file, we need to load the key from the saved file. We will read the key from the file and store it in a variable.
with open('key.txt', 'rb') as key_file:
key = key_file.read()
Step 5: Encrypt the file
Now that we have the key, we can start encrypting a file. In this example, we will encrypt a text file, but you can encrypt any type of file using the same approach.
# Read the file content
with open('plaintext.txt', 'rb') as file:
plaintext = file.read()
# Create a Fernet object with the key
fernet = Fernet(key)
# Encrypt the file content
encrypted = fernet.encrypt(plaintext)
# Save the encrypted content to a new file
with open('encrypted.txt', 'wb') as file:
file.write(encrypted)
Step 6: Decrypt the file
To decrypt the encrypted file, we will follow a similar process. First, we load the key from the saved file, then we read the encrypted content from the file and decrypt it using the key.
# Load the key from the file
with open('key.txt', 'rb') as key_file:
key = key_file.read()
# Read the encrypted content
with open('encrypted.txt', 'rb') as file:
encrypted = file.read()
# Create a Fernet object with the key
fernet = Fernet(key)
# Decrypt the encrypted content
decrypted = fernet.decrypt(encrypted)
# Save the decrypted content to a new file
with open('decrypted.txt', 'wb') as file:
file.write(decrypted)
And that's it! You have successfully encrypted and decrypted a file using Python. Remember to replace the filenames and paths in the code with your own file names and paths.