Question: Objectives: Familiarize the student with: Practice Python tools to encrypt and decrypt files; Account for missing files; Task: Consider the Python .py file(s) provided with
Objectives:
Familiarize the student with:
- Practice Python tools to encrypt and decrypt files;
- Account for missing files;
Task:
Consider the Python .py file(s) provided with this assignment on Blackboard and modify the code to meet the following requirements:
- Complete the main function that will run whenever the module is called;
- The main function should interact with the user and allow the user to specify whether he or she want to encrypt or decrypt;
- The user should be allowed to choose between 1) the insecure mode where the encryption key file is saved for usage in decryption or 2) a more secure way where the key is generated whenever it is used through a passphrase;
- The user should be allowed to input the file to encrypt or decrypt;
- When a user input the file to encrypt, the program should identify the file extension explicitly. That same extension should be added to the encrypted file and the decrypted file.
- The program should be able to run from the command line interface and the python shell. Demonstrate both and submit screenshots of your demonstration.
-
from cryptography.fernet import Fernet
import os.path, sys
def key_gene():
#create a key
my_Key = Fernet.generate_key()
#write the key to a file
with open("my_kkey.key", "wb") as kf:
kf.write(my_Key)
#print the size of the key file
print(f"Size of the key file is {os.path.getsize('my_kkey.key')} Bytes")
return(my_Key)
def encryption(f2encrypt):
#get the key from the key_gene function
key = key_gene()
fu = Fernet(key) #tool with the key
#get the file
with open(f2encrypt, 'rb') as file:
file_data = file.read()
#encrypt the file
encrypted_data = fu.encrypt(file_data)
with open('new_file.txt', 'wb') as f:
f.write(encrypted_data)
#print file sizes
print(f"Size of the file to encrypt is {os.path.getsize(f2encrypt)} Bytes")
print(f"Size of the encrypted file is {os.path.getsize('new_file.txt')} Bytes")
#decrypt
def decryption(file2decrypt, key_file):
print('Trying to decrypt!')
#read the key file as a binary and buld the tool with the key
key = ''
with open(key_file, 'rb') as f:
key = f.read()
fu = Fernet(key)
#open the file to decrypt as a byte Python object
data2decrypt = ''
with open(file2decrypt, 'rb') as f:
data2decrypt = f.read()
#decryption
decrypted_data = fu.decrypt(data2decrypt)
#Save the decrypted data to a file named 'decrypted_file'
with open('decrypted_file.txt', 'wb') as f:
f.write(decrypted_data)
if __name__ == '__main__':
encryption('file1.txt') #I added an option to select how the encryption will be done
decryption('new_file.txt', 'my_kkey.key')
#
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
