output_filename will store the encrypted data.
We are reading the secret key from the file as a string. So, we would need to encode the string to get bytes. We would use the encoded bytes to initialize the Fernet.
Once the Fernet is initialized, we can read the data from the input file, encrypt the data and store it in the output file. Please note that Fernet.encrypt() method takes bytes as arguments and file.write() method takes a string as an argument. So, we need to encode and decode the data respectively.
The decryption function can be implemented in the following way:
def decrypt_file(encrypted_filename, key_filename, filename):
with open(key_filename, "r") as key_file:
key = key_file.read()
fernet = Fernet(key.encode())
with open(encrypted_filename, "r") as file:
data = file.read()
decrypted_text = fernet.decrypt(data.encode())
with open(filename, "w") as output_file:
output_file.write(decrypted_text.decode())
Here, we are taking encrypted_filename as input, reading the encrypted data from the file. We are also reading the secret key from the key file. After retrieving the key from the key file, we are decrypting the encrypted data and storing the decrypted data in another file filename. Here also we would need to use encode and decode to convert a string into bytes and bytes into a string respectively.
The complete code for encryption and decryption of file using Python is given below:
from cryptography.fernet import Fernet
def generate_private_key(key_file):
key = Fernet.generate_key()
with open(key_file, "w") as file:
file.write(key.decode())
def encrypt_file(filename, key_filename, output_filename):
with open(key_filename, "r") as key_file:
key = key_file.read()
fernet = Fernet(key.encode())
with open(filename, "r") as file:
data = file.read()
token = fernet.encrypt(data.encode())
with open(output_filename, "w") as output_file:
output_file.write(token.decode())
def decrypt_file(encrypted_filename, key_filename, filename):
with open(key_filename, "r") as key_file:
key = key_file.read()
fernet = Fernet(key.encode())
with open(encrypted_filename, "r") as file:
data = file.read()
decrypted_text = fernet.decrypt(data.encode())
with open(filename, "w") as output_file:
output_file.write(decrypted_text.decode())
filename = "test.txt"
key_file = "private_key.txt"
encrypted_file = "encrypted_test.txt"
generate_private_key(key_file)
encrypt_file(filename, key_file, encrypted_file)
decrypt_file(encrypted_file, key_file, filename)
I hope this helps. However, readers who want to know more about how different cryptographic algorithms work and how they are used in various secure network protocols can refer to the book “Cryptography And Public Key Infrastructure.”










































0 Comments