In this article, we would discuss how to encrypt and decrypt files using Python. We would take a file name as input, encrypt it and store it in an output file. Also, we would generate a secret key securely and store the secret key in a file. Later, we would read that key file, retrieve the secret key and decrypt the encrypted file using the secret key.
In our previous article, we discussed how to use Fernet for encryption and decryption. In this article, we would use Fernet to encrypt and decrypt a file. Interested readers who want to know more about Fernet, please refer to the said article.
How to encrypt and decrypt a file using Python?
We would first use Fernet to generate a secret key. We need to store the secret key in a file so that we can read the secret key later for decryption. Otherwise, we can use our own secret key.
def generate_private_key(key_file): key = Fernet.generate_key() with open(key_file, "w") as file: file.write(key.decode())
Please note that file.write() function takes a string as an argument. But, the generated key is in bytes. So, we are decoding the generated key to convert the bytes into a string.
We can use this secret key to encrypt a file in the following way:
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())
Here, we are encrypting the filename file. The key_filename file stores the secret key. And, …
0 Comments