|
| 1 | +from cryptography.fernet import Fernet |
| 2 | +# Generating a key |
| 3 | +def write_key(): |
| 4 | + """ |
| 5 | + Generates a key and save it into a file |
| 6 | + """ |
| 7 | + key = Fernet.generate_key() |
| 8 | + |
| 9 | + with open('key.key', "wb") as key_file: |
| 10 | + key_file.write(key) |
| 11 | + print('Key Generated!!!') |
| 12 | +# loading our key |
| 13 | +def load_key(): |
| 14 | + """ |
| 15 | + Loads the key from the current directory named `key.key` |
| 16 | + """ |
| 17 | + return open('key.key', "rb").read() |
| 18 | +# function for encrypting our file |
| 19 | +def encrypt(filename, key): |
| 20 | + """ |
| 21 | + Given a filename (str) and key (bytes), it encrypts the file and write it |
| 22 | + """ |
| 23 | + f = Fernet(key) |
| 24 | + with open(filename, "rb") as file: |
| 25 | + # read all file data |
| 26 | + file_data = file.read() |
| 27 | + # encrypt data |
| 28 | + encrypted_data = f.encrypt(file_data) |
| 29 | + # write the encrypted file |
| 30 | + with open(filename, "wb") as file: |
| 31 | + file.write(encrypted_data) |
| 32 | + |
| 33 | +def encrypt_file(): |
| 34 | + file = input('File name: ') |
| 35 | + key = load_key() |
| 36 | + encrypt(file,key) |
| 37 | + print('File Encrypted!!!') |
| 38 | +# function for decrypting our file |
| 39 | +def decrypt(filename, key): |
| 40 | + """ |
| 41 | + Given a filename (str) and key (bytes), it decrypts the file and write it |
| 42 | + """ |
| 43 | + f = Fernet(key) |
| 44 | + with open(filename, "rb") as file: |
| 45 | + # read the encrypted data |
| 46 | + encrypted_data = file.read() |
| 47 | + # decrypt data |
| 48 | + decrypted_data = f.decrypt(encrypted_data) |
| 49 | + # write the original file |
| 50 | + with open(filename, "wb") as file: |
| 51 | + file.write(decrypted_data) |
| 52 | + |
| 53 | +def decrypt_file(): |
| 54 | + file = input('File name: ') |
| 55 | + key = load_key() |
| 56 | + decrypt(file,key) |
| 57 | + print('File Decrypted!!!') |
| 58 | + |
| 59 | + |
0 commit comments