To set the stage, why encryption is important in the first place. Imagine this: you’ve just finished writing your masterpiece novel, but before you can publish it, someone hacks into your computer and steals your manuscript. Now what? You could cry yourself to sleep for weeks or you could encrypt that sucker!
Encryption works by converting plain text (like your novel) into ciphertext a scrambled mess of characters that only the intended recipient can decipher. And guess what, Python has some pretty awesome libraries for doing just that! Let’s take a look at one called Crypto.Cipher.
To get started, let’s create a new file and call it `encrypt_file.py`. We’ll use this script to encrypt our novel using the Advanced Encryption Standard (AES) algorithm with a 256-bit key. Here’s what we need:
# Import the necessary library for AES encryption
from Crypto.Cipher import AES
# Import the operating system library
import os
# Set up variables for input and output files
input_file = "your_novel.txt" # Input file name
output_file = "encrypted_novel.bin" # Output file name
key = b'YOUR_SECRET_KEY' # Secret key used for encryption, must be in bytes format
# Read in the input file as bytes
with open(input_file, 'rb') as f: # Open the input file in read-only mode and assign it to variable f
data = f.read() # Read the contents of the file and assign it to variable data
# Create a new AES cipher object and initialize it with our secret key
cipher = AES.new(key) # Create a new AES cipher object with the given secret key
# Encrypt the data using CBC mode (for added security)
encrypted_data = b'' # Create an empty bytes object to store the encrypted data
iv = cipher.nonce # Generate a random initialization vector (IV) and assign it to variable iv
encrypted_data += iv + cipher.encrypt(data) # Encrypt the data using the AES cipher and append the IV to the beginning of the encrypted data
# Write the encrypted data to a binary file
with open(output_file, 'wb') as f: # Open the output file in write-only mode and assign it to variable f
f.write(encrypted_data) # Write the encrypted data to the file
Now let’s break down what we just did here! First, we imported two libraries Crypto and os (for working with files). Then we set up some variables for our input and output files, as well as a secret key that you should replace with your own. We read in the input file using binary mode (‘rb’) to ensure that we get all of the bytes, including any special characters or whitespace.
Next, we created a new AES cipher object and initialized it with our secret key. This is where the magic happens! The `encrypt()` method takes care of converting our plain text into ciphertext using the Advanced Encryption Standard (AES) algorithm. We also used CBC mode for added security, which ensures that each block of data is encrypted based on the previous one making it harder to crack the encryption if only part of the message is intercepted.
Finally, we wrote the encrypted data to a binary file using ‘wb’ mode (for writing in binary format). Your novel is now securely encrypted and ready for publication.
But wait what about decryption? How do you get your novel back once it’s been encrypted? Well, that’s easy too! Let’s create a new script called `decrypt_file.py`:
# Import necessary libraries
from Crypto.Cipher import AES # Import AES module from Crypto library for encryption and decryption
import os # Import os module for file operations
# Set up variables for input and output files
input_file = "encrypted_novel.bin" # Set input file name
output_file = "your_novel.txt" # Set output file name
key = b'YOUR_SECRET_KEY' # Set secret key for encryption and decryption. Note: This should be kept confidential and not shared with anyone.
# Read in the encrypted file as bytes
with open(input_file, 'rb') as f: # Open input file in read and binary mode
data = f.read() # Read the contents of the file and store it in a variable called data
# Extract the IV and ciphertext from the input data
iv = data[:16] # Extract the first 16 bytes of data as the initialization vector (IV)
ciphertext = data[16:] # Extract the remaining data as the ciphertext
# Create a new AES cipher object and initialize it with our secret key
cipher = AES.new(key) # Create a new AES cipher object with the specified secret key
# Decrypt the ciphertext using CBC mode (for added security)
decrypted_data = b'' # Create an empty variable to store the decrypted data
decrypted_data += iv + cipher.decrypt(ciphertext, initial_associated_data=iv) # Decrypt the ciphertext using the specified IV and store the result in the decrypted_data variable
# Write the decrypted data to a text file
with open(output_file, 'wb') as f: # Open output file in write and binary mode
f.write(decrypted_data) # Write the decrypted data to the file
Again, we imported Crypto and os libraries for working with files. We set up variables for our input and output files, as well as the secret key that you should replace with your own. This time, however, we read in the encrypted file using binary mode (‘rb’) to ensure that we get all of the bytes including the IV (initialization vector) and ciphertext.
We then extracted the IV from the input data by slicing it off using `data[:16]`. The remaining bytes are our ciphertext, which we’ll decrypt using CBC mode for added security. We also used initial_associated_data to ensure that each block of data is decrypted based on the previous one making it harder to crack the encryption if only part of the message is intercepted.
Finally, we wrote the decrypted data to a text file using ‘wb’ mode (for writing in binary format). Your novel is now back in its original form and ready for publication.
With just a few lines of code, your secrets are safe from prying eyes. But remember, always use strong keys and keep them secret!