How to create file encryption/decryption program using Python

Securing sensitive information has become a top priority in the increasingly digital world. Whether it’s personal data, confidential business documents, or financial records, ensuring that data remains private during transmission and storage is crucial. File encryption and decryption are powerful techniques that provide a robust layer of security. In this Answer, we’ll explore how to create a file encryption and decryption program using Python.

Building this file encryption/decryption program will introduce us to the intriguing world of data security and cryptography while reinforcing fundamental programming concepts. As we journey through crafting this program, we’ll delve into essential topics such as input handling, cryptographic algorithms, and file manipulation. We’ll use the cryptography library, which provides a high-level interface for encryption and decryption.

Overview of encryption/decryption
Overview of encryption/decryption

Encryption

Encryption involves converting plain, readable data (plaintext) into an unreadable format (ciphertext) using an algorithm and an encryption key. This transformation ensures that only authorized parties with the decryption key can access and understand the original data.

For instance, consider the sentence:

Hello, this is a confidential message.

This sentence is the plaintext that we want to protect. When we apply encryption using a key, it might result in ciphertext like:

7f2c8e6b4d1a9f0e3c7b2d8a1f6e0d

This ciphertext appears as a seemingly random sequence of characters, providing a strong layer of security against prying eyes.

Generating an encryption key

Let’s harness the power of Python and the cryptography library to generate our encryption key. This process creates a cryptographically secure key, ensuring its strength is derived from true randomness.

from cryptography.fernet import Fernet # Import the necessary module from the cryptography library
# Generate a random encryption key
def generate_key():
return Fernet.generate_key() # Generate a 32-byte encryption key using Fernet
# Generate an encryption key
key = generate_key() # Call the generate_key function to create the encryption key
print("Encryption Key:", key) # Print the generated encryption key
Generating encryption key

With the encryption key in our possession, we’ve established the crucial first link in the chain of security, which is vital for protecting our sensitive information. An encryption key plays a foundational role in the field of cryptography, acting as a digital ‘lock’ that safeguards the intricate mechanisms of data protection. Similar to a physical key for a locked door, an encryption key provides access to the realm of secure communication.

As we continue on this journey towards heightened security, this key assumes the role of a cornerstone in our encryption and decryption efforts. It possesses the remarkable ability to metamorphose seemingly ordinary files into impenetrable strongholds of data protection. Imagine it as a potent spell that, when cast, envelops your data in an invisible cloak of unreadability, rendering it incomprehensible to unauthorized eyes.

Encrypting the file

Now let’s encapsulate the essence of encryption. First, we will read the content of a file named plaintext.txt, encases it within an unbreakable cipher, and stores the encrypted result in a new file with the extension .encrypted.

main.py
plaintext.txt
from cryptography.fernet import Fernet
# Generate a random encryption key
def generate_key():
return Fernet.generate_key()
# Encrypt the contents of a file using the provided key
def encrypt_file(filename, key):
cipher_suite = Fernet(key) # Initialize a Fernet object with the encryption key
with open(filename, 'rb') as file:
plaintext = file.read() # Read the plaintext data from the file
encrypted_data = cipher_suite.encrypt(plaintext) # Encrypt the plaintext data
with open(filename + '.encrypted', 'wb') as encrypted_file:
encrypted_file.write(encrypted_data) # Write the encrypted data to a new file
# Generate an encryption key
key = generate_key()
# Specify the source file to be encrypted
source_file = 'plaintext.txt'
# Encrypt the file using the generated key
encrypt_file(source_file, key)
# Inform the user about the successful encryption
print(f'{source_file} encrypted.') # Print a message indicating successful encryption
# Print the encrypted content in hexadecimal format
encrypted_filename = source_file + '.encrypted'
with open(encrypted_filename, 'rb') as encrypted_file:
encrypted_data = encrypted_file.read()
encrypted = encrypted_data.hex()
print("Encrypted Content:", encrypted)
Encrypting the file

In this code:

  1. In line 1, we import the necessary module, Fernet, which grants us the power to transform data into its encrypted form.
  2. The encrypt_file function from lines 8–14 orchestrates the encryption process. It opens the specified file, reads the plaintext data, encrypts it, and then writes the encrypted data to a new file with the .encrypted extension.
  3. We generate an encryption key using the generate_key function which is at line 4.
  4. The variable source_file denotes the file we wish to protect. By calling the encrypt_file function with this source file and the generated encryption key, we initiate the encryption process on line 23.
  5. Lastly in lines 30–33, we print the encrypted data, since the encrypted content is still not human-readable, converting it to hexadecimal format provides a glimpse into the nature of the encrypted data.

Decryption

Decryption is the process that elegantly undoes encryption transformation, converting ciphertext back into its original, human-readable form. It serves as the counterpart to encryption, allowing authorized parties to access and comprehend the information that was securely protected.

Decrypting the file

To decrypt the encrypted file, we’ll need the same encryption key. Here’s how we can implement the decryption process:

main.py
plaintext.txt
from cryptography.fernet import Fernet
# Generate a random encryption key
def generate_key():
return Fernet.generate_key()
# Encrypt the contents of a file using the provided key
def encrypt_file(filename, key):
cipher_suite = Fernet(key) # Initialize a Fernet object with the key
with open(filename, 'rb') as file:
plaintext = file.read() # Read the plaintext data from the file
encrypted_data = cipher_suite.encrypt(plaintext) # Encrypt the plaintext
with open(filename + '.encrypted', 'wb') as encrypted_file:
encrypted_file.write(encrypted_data) # Write the encrypted data to a new file
# Decrypt the contents of an encrypted file using the provided key
def decrypt_file(encrypted_filename, key):
cipher_suite = Fernet(key) # Initialize a Fernet object with the key
with open(encrypted_filename, 'rb') as encrypted_file:
encrypted_data = encrypted_file.read() # Read the encrypted data from the file
decrypted_data = cipher_suite.decrypt(encrypted_data) # Decrypt the data
decrypted_filename = encrypted_filename.replace('.encrypted', '.decrypted') # Generate a new filename
with open(decrypted_filename, 'wb') as decrypted_file:
decrypted_file.write(decrypted_data) # Write the decrypted data to a new file
key = generate_key() # Generate an encryption key
source_file = 'plaintext.txt' # Specify the source file to be encrypted
# Encrypt the file using the generated key
encrypt_file(source_file, key)
encrypted_file = source_file + '.encrypted' # Generate the name of the encrypted file
# Decrypt the encrypted file using the same key
decrypt_file(encrypted_file, key)
# Inform the user about the successful decryption
print(f'{encrypted_file} decrypted.')
# Print the content of the decrypted file
decrypted_filename = source_file + '.decrypted'
with open(decrypted_filename, 'r') as decrypted_file:
decrypted_content = decrypted_file.read()
print("Decrypted Content:\n", decrypted_content)
Decrypting the file

In this code:

  1. The decrypt_file function is introduced in line 17, acting as the key player in the decryption process.
  2. A Fernet object is initialized with the decryption key in line 18, following the same pattern as encryption.
  3. The encrypted data is read from the .encrypted file in lines 19–20.
  4. The .decrypt() method is invoked on the cipher suite object to reverse the encryption process and obtain the original plaintext data in line 21.
  5. In line 22, a new filename is generated to save the decrypted content with the .decrypted extension.
  6. The decrypted content is read from the .decrypted file and printed, presenting the original, human-readable data in lines 41–44.

In our journey through the intricacies of file encryption and decryption using Python, we have fortified our data against prying eyes. Encryption, the art of transforming information into an unreadable cipher, empowers us to shield our files from unauthorized access.

With the cryptography library as our guide, we have generated encryption keys, unlocking the door to impervious data protection. We have witnessed how encryption converts files into enigmas, and decryption unveils their true essence.

As we grasp the power of encryption and decryption, we are prepared to navigate the digital realm with heightened security. Armed with Python, we have acquired the tools to safeguard sensitive information and champion data integrity. Remember, the path to digital fortification is now at our fingertips—unravel, secure, and embark on a future of confident data handling.

Copyright ©2024 Educative, Inc. All rights reserved