07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

178 Chapter 6 ■ Using Cryptography with Images

file_data = file.read()

# encrypt data

encrypted_data = f.encrypt(file_data)

# write the encrypted file

with open(filename, "wb") as file:

file.write(encrypted_data)

def decrypt(filename, key):

# decrypts the file and writes it using the filename and key

f = Fernet(key)

with open(filename, "rb") as file:

# read the encrypted data

encrypted_data = file.read()

# decrypt data

decrypted_data = f.decrypt(encrypted_data)

# write the original file

with open(filename, "wb") as file:

file.write(decrypted_data)

if __name__ == "__main__":

import argparse

parser = argparse.ArgumentParser(description="Simple File Encryptor

Script")

parser.add_argument("file", help="File to encrypt/decrypt")

parser.add_argument("-g", "--generate-key", dest="generate_key",

action="store_true",

help="Whether to generate a new key or use

existing")

parser.add_argument("-e", "--encrypt", action="store_true",

help="Whether to encrypt the file, only -e or -d

can be specified.")

parser.add_argument("-d", "--decrypt", action="store_true",

help="Whether to decrypt the file, only -e or -d

can be specified.")

args = parser.parse_args()

file = args.file

generate_key = args.generate_key

if generate_key:

write_key()

# load the key

key = load_key()

encrypt_ = args.encrypt

decrypt_ = args.decrypt

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!